#!/usr/bin/env node import { createRequire } from "node:module"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { existsSync, readFileSync } from "node:fs"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const defaultStorageRoot = resolve(repoRoot, ".voidbot"); const defaultStatusDir = resolve(defaultStorageRoot, "status"); const defaultSnapshotPath = resolve(defaultStatusDir, "swarm-state.json"); const defaultDashboardPath = resolve(defaultStatusDir, "swarm-dashboard.html"); const defaultCultMeshStorePath = resolve(defaultStatusDir, "cultmesh", "voidbot-swarm-state.cc"); const providerId = "voidbot.swarm"; const verseId = "voidbot.local"; const snapshotDocumentType = "voidbot.swarm_state_snapshot"; const snapshotSchemaId = "voidbot.swarm_state_snapshot.v1"; const providerAdvertisementDocumentType = "gamecult.eve.provider_advertisement"; const providerAdvertisementSchemaId = "gamecult.eve.provider_advertisement.v1"; const eveBindingDocumentType = "gamecult.eve.interface_binding"; const eveBindingSchemaId = "gamecult.eve.interface_binding.v1"; const surfaceDocumentType = "gamecult.eve.surface_state"; const surfaceSchemaId = "gamecult.eve.surface_state.v1"; const providerCatalogDocumentType = "voidbot.provider_advertisement_catalog"; const providerCatalogSchemaId = "voidbot.provider_advertisement_catalog.v0"; const transportProfileDocumentType = "idunn.daemon_transport_profile"; const transportProfileSchemaId = "idunn.daemon_transport_profile.v1"; const commandBoundaryDocumentType = "idunn.command_boundary"; const commandBoundarySchemaId = "idunn.command_boundary.v1"; const swarmControlDocumentType = "voidbot.swarm_control_state"; const swarmControlSchemaId = "voidbot.swarm_control_state.v1"; const args = parseArgs(process.argv.slice(2)); const env = await readDotEnv(resolve(repoRoot, ".env")); const swarmCultMeshRudpEndpoint = String( args.rudpEndpoint || args["rudp-endpoint"] || process.env.VOIDBOT_SWARM_CULTMESH_RUDP || env.VOIDBOT_SWARM_CULTMESH_RUDP || "rudp://127.0.0.1:17873", ).trim(); const storageRoot = resolveConfigPath(env.STORAGE_ROOT, defaultStorageRoot); const statusDir = resolve(storageRoot, "status"); const heartbeatStatePath = resolveConfigPath( env.REPO_FACE_HEARTBEAT_STATE_PATH, resolve(statusDir, "repo-face-heartbeats.json"), ); const orchestratorPath = resolve(statusDir, "gamecult-orchestrator.json"); const pausePath = resolve(repoRoot, "state", "agent-swarm-paused.json"); const snapshotPath = resolveConfigPath(args.snapshot, defaultSnapshotPath.replace(defaultStatusDir, statusDir)); const dashboardPath = resolveConfigPath(args.out, defaultDashboardPath.replace(defaultStatusDir, statusDir)); const cultMeshStorePath = resolveConfigPath( args.cultmeshStore, defaultCultMeshStorePath.replace(defaultStatusDir, statusDir), ); const requireCultMeshAdvertisement = !isFlagEnabled(args.public) && !isFlagEnabled(args.allowUnmeshed); const renderResult = await render(); if (args.open) { console.log(pathToFileURL(renderResult.dashboardPath).href); } if (args.serve) { throw new Error("VoidBot swarm is exposed through CultMesh/Eve, not a web server. Use npm run swarm:render-dashboard to publish the CultMesh surface."); } else { console.log(`Swarm dashboard HTML: ${renderResult.dashboardPath}`); console.log(`Swarm snapshot JSON: ${renderResult.snapshotPath}`); console.log(`CultMesh snapshot store: ${renderResult.cultMeshStorePath}`); } async function render() { let snapshot = await buildSnapshot(); if (isFlagEnabled(args.public)) { snapshot = redactSnapshot(snapshot); } await mkdir(dirname(snapshotPath), { recursive: true }); await mkdir(dirname(dashboardPath), { recursive: true }); const pendingEveState = buildEveProviderState(snapshot); const cultMeshWrite = await writeCultMeshPublication(snapshot, pendingEveState, cultMeshStorePath); if (requireCultMeshAdvertisement && cultMeshWrite.writeStatus !== "ok") { throw new Error(`VoidBot swarm CultMesh advertisement failed: ${cultMeshWrite.writeError ?? cultMeshWrite.writeStatus}`); } const finalSnapshot = { ...snapshot, cultMesh: { ...snapshot.cultMesh, ...cultMeshWrite, }, }; const finalEveState = buildEveProviderState(finalSnapshot); const finalCultMeshWrite = await writeCultMeshPublication(finalSnapshot, finalEveState, cultMeshStorePath, false); if (requireCultMeshAdvertisement && finalCultMeshWrite.writeStatus !== "ok") { throw new Error(`VoidBot swarm final CultMesh surface publish failed: ${finalCultMeshWrite.writeError ?? finalCultMeshWrite.writeStatus}`); } finalSnapshot.cultMesh = { ...finalSnapshot.cultMesh, ...finalCultMeshWrite, }; await writeFile(snapshotPath, `${JSON.stringify(finalSnapshot, null, 2)}\n`, "utf8"); await writeFile(dashboardPath, renderHtml(finalSnapshot), "utf8"); return { dashboardPath, snapshotPath, cultMeshStorePath, }; } async function buildSnapshot() { const now = new Date(); const heartbeat = await readJsonFile(heartbeatStatePath); const orchestrator = await readJsonFile(orchestratorPath); const pause = await readJsonFile(pausePath); const identityMetadata = await readIdentityMetadata(env.REPO_DISCORD_IDENTITIES_PATH); const heartbeatMtime = await getMtime(heartbeatStatePath); const orchestratorMtime = await getMtime(orchestratorPath); const paused = pause.ok ? pause.value?.paused !== false : false; const pauseReason = pause.ok && typeof pause.value?.reason === "string" ? pause.value.reason : undefined; const participants = Array.isArray(heartbeat.value?.participants) ? heartbeat.value.participants : []; const pendingMentions = Array.isArray(heartbeat.value?.pendingMentions) ? heartbeat.value.pendingMentions : []; const initiativeClock = numberOrNull(heartbeat.value?.initiativeClock); const participantSnapshots = participants.map((participant) => projectParticipant(participant, pendingMentions, initiativeClock, identityMetadata), ); const faceStates = await readFaceStates(identityMetadata); for (const participant of participantSnapshots) { participant.faceState = faceStates.get(participant.identityId.toLowerCase()) ?? { readable: false, path: participant.faceStatePath, error: participant.faceStatePath ? "State file was not readable." : "No Face state path registered.", tree: [], }; participant.restState = participant.faceState.restState ?? null; } const activeTurns = participantSnapshots.filter((participant) => participant.activeJobId); const readyNow = participantSnapshots.filter((participant) => participant.status === "active" && !participant.activeJobId && participant.restState?.isNapping !== true && typeof participant.nextTurnInMinutes === "number" && participant.nextTurnInMinutes <= 0, ); const nextParticipant = [...participantSnapshots] .filter((participant) => typeof participant.nextTurnInMinutes === "number") .sort((left, right) => left.nextTurnInMinutes - right.nextTurnInMinutes)[0]; const organs = projectOrgans(orchestrator.value); const recentEvents = Array.isArray(heartbeat.value?.history) ? heartbeat.value.history.slice(-24).reverse().map(projectHistoryEvent) : []; const recentMentionActivity = buildRecentMentionActivity(heartbeat.value?.history, pendingMentions); const controls = projectControls(heartbeat.value?.controls); const upcomingTurns = buildUpcomingTurns(participantSnapshots); const lastShuffle = findLastShuffleEvent(recentEvents); const lastMentionActivity = recentMentionActivity[0] ?? null; return { schemaVersion: snapshotSchemaId, generatedAt: now.toISOString(), title: "VoidBot Swarm State", sources: { heartbeatStatePath, heartbeatStateUpdatedAt: heartbeatMtime, heartbeatStateReadable: heartbeat.ok, heartbeatStateError: heartbeat.ok ? undefined : heartbeat.error, orchestratorPath, orchestratorUpdatedAt: orchestratorMtime, orchestratorReadable: orchestrator.ok, orchestratorError: orchestrator.ok ? undefined : orchestrator.error, pausePath, pauseReadable: pause.ok, pauseError: pause.ok ? undefined : pause.error, }, cultMesh: { documentType: snapshotDocumentType, schemaId: snapshotSchemaId, documentKey: "voidbot-swarm", storePath: cultMeshStorePath, writeStatus: "pending", providerId, verseId, eveDeckEndpoint: primaryCultMeshEndpoint(), note: "VoidBot swarm is a CultMesh-advertised Eve provider. The web page is a local lowering of the same surface.", }, summary: { state: deriveSwarmState({ heartbeat, orchestrator, paused, activeTurns }), paused, pauseReason, participantCount: participantSnapshots.length, activeTurnCount: activeTurns.length, pendingMentionCount: pendingMentions.length, recentMentionActivityCount: recentMentionActivity.length, lastMentionActivity, readyNowCount: readyNow.length, nextIdentityId: nextParticipant?.identityId ?? null, nextDisplayName: nextParticipant?.displayName ?? null, nextTurnInMinutes: nextParticipant?.nextTurnInMinutes ?? null, initiativeClock, baseRecoveryMinutes: numberOrNull(heartbeat.value?.baseRecoveryMinutes), globalHeat: numberOrNull(heartbeat.value?.globalHeat), cadenceMultiplier: controls.cadenceMultiplier, lastTickAt: stringOrNull(heartbeat.value?.lastTickAt), lastShuffle, }, controls, upcomingTurns, participants: participantSnapshots, activeTurns, pendingMentions: pendingMentions.map(projectPendingMention), recentMentionActivity, orchestrator: { state: deriveOrchestratorState(organs), organs, }, recentEvents, }; } function projectControls(value) { const cadenceMultiplier = numberOrNull(value?.cadenceMultiplier) ?? 1; const manualTurnRequests = Array.isArray(value?.manualTurnRequests) ? value.manualTurnRequests.slice(-12).reverse().map((request) => ({ id: stringOrNull(request?.id), identityId: stringOrNull(request?.identityId), requestedAt: stringOrNull(request?.requestedAt), status: stringOrNull(request?.status) ?? "pending", note: stringOrNull(request?.note), })) : []; return { cadenceMultiplier, updatedAt: stringOrNull(value?.updatedAt), manualTurnRequests, }; } function buildUpcomingTurns(participants) { const ordered = [...participants] .filter((participant) => participant.status === "active") .sort((left, right) => { const activeDelta = Number(Boolean(right.activeJobId)) - Number(Boolean(left.activeJobId)); if (activeDelta) return activeDelta; return (left.nextTurnInMinutes ?? 999999) - (right.nextTurnInMinutes ?? 999999); }) .slice(0, 16); const maxMinutes = Math.max(1, ...ordered.map((participant) => Math.max(0, participant.nextTurnInMinutes ?? 0))); return ordered.map((participant, index) => ({ identityId: participant.identityId, displayName: participant.displayName, repoName: participant.repoName, avatarUrl: participant.avatarUrl, participantKind: participant.participantKind, activeJobId: participant.activeJobId, restState: participant.restState, pendingMentionCount: participant.pendingMentionCount, shuffleReason: participant.pendingMentionCount > 0 ? "mention" : participant.activeJobId ? "active" : participant.restState?.isNapping === true ? "nap" : null, nextTurnInMinutes: participant.nextTurnInMinutes, effectiveSpeed: participant.effectiveSpeed, heat: participant.heat, dynamicHeat: participant.dynamicHeat, responsePressure: participant.responsePressure, lane: index % 3, timelinePosition: participant.activeJobId ? 0 : Math.min(100, Math.max(0, ((Math.max(0, participant.nextTurnInMinutes ?? 0)) / maxMinutes) * 100)), })); } function findLastShuffleEvent(events) { const directMention = events.find((event) => event.type === "queued" && typeof event.pendingMentionCount === "number" && event.pendingMentionCount > 0 ); if (directMention) { return { kind: "direct_mention", identityId: directMention.identityId, observedAt: directMention.observedAt, }; } const manual = events.find((event) => event.type === "manual_turn_override_applied"); if (manual) { return { kind: "manual_override", identityId: manual.identityId, observedAt: manual.observedAt, }; } return null; } function projectParticipant(participant, pendingMentions, initiativeClock, identityMetadata) { const identityId = String(participant.identityId ?? "unknown"); const metadata = identityMetadata.get(identityId.toLowerCase()) ?? {}; const nextTurnAt = numberOrNull(participant.nextTurnAt); const lastTurnAt = numberOrNull(participant.lastTurnAt); const activeTurnStartedAt = numberOrNull(participant.activeTurnStartedAt); const channelCount = Array.isArray(participant.groups) ? participant.groups.filter((entry) => typeof entry === "string" && entry.startsWith("channel:")).length : 0; const mentionCount = pendingMentions.filter((mention) => mention?.identityId === identityId).length; const nextTurnInMinutes = typeof nextTurnAt === "number" && typeof initiativeClock === "number" ? round(nextTurnAt - initiativeClock, 3) : null; return { identityId, displayName: String(participant.displayName ?? metadata.displayName ?? identityId), repoName: String(participant.repoName ?? metadata.repoName ?? "unknown"), repoPath: stringOrNull(metadata.repoPath), faceStatePath: stringOrNull(metadata.faceStatePath), personaStatePath: stringOrNull(metadata.personaStatePath), description: stringOrNull(metadata.description), avatarUrl: metadata.avatarUrl ?? null, avatarPath: metadata.avatarPath ?? null, channelPermissions: Array.isArray(metadata.channelPermissions) ? metadata.channelPermissions.slice(0, 12).map((entry) => ({ label: stringOrNull(entry?.label), topic: stringOrNull(entry?.topic), speechThreshold: stringOrNull(entry?.speechThreshold), speedMultiplier: numberOrNull(entry?.speedMultiplier), })) : [], participantKind: String(participant.participantKind ?? "repo_face"), turnKind: String(participant.turnKind ?? "repo_face_rumination"), status: String(participant.status ?? "unknown"), currentLoad: numberOrNull(participant.currentLoad), heat: numberOrNull(participant.heat), dynamicHeat: numberOrNull(participant.dynamicHeat), responsePressure: numberOrNull(participant.responsePressure), responsePressureEvidence: Array.isArray(participant.responsePressureEvidence) ? participant.responsePressureEvidence.slice(0, 6).map((entry) => ({ messageId: stringOrNull(entry?.messageId), observedAt: stringOrNull(entry?.observedAt), similarity: numberOrNull(entry?.similarity), contribution: numberOrNull(entry?.contribution), })) : [], effectiveSpeed: numberOrNull(participant.effectiveSpeed), initiativeSpeed: numberOrNull(participant.initiativeSpeed), nextTurnAt, nextTurnInMinutes, lastTurnAt, activeTurnStartedAt, activeJobId: stringOrNull(participant.activeJobId), lastQueuedAt: stringOrNull(participant.lastQueuedAt), queuedCount: numberOrNull(participant.queuedCount), pendingMentionCount: mentionCount, channelCount, constraintCount: Array.isArray(participant.constraints) ? participant.constraints.length : 0, constraints: Array.isArray(participant.constraints) ? participant.constraints.slice(0, 4).map(String) : [], }; } function projectOrgans(orchestrator) { const organs = orchestrator?.organs && typeof orchestrator.organs === "object" ? orchestrator.organs : {}; return Object.entries(organs).map(([id, organ]) => ({ id, label: String(organ?.label ?? id), intervalMinutes: numberOrNull(organ?.intervalMinutes), lastStartedAt: stringOrNull(organ?.lastStartedAt), lastFinishedAt: stringOrNull(organ?.lastFinishedAt), lastExitCode: numberOrNull(organ?.lastExitCode), lastStatus: String(organ?.lastStatus ?? "unknown"), lastLogPath: stringOrNull(organ?.lastLogPath), cultMeshServer: organ?.cultMeshServer && typeof organ.cultMeshServer === "object" ? { status: stringOrNull(organ.cultMeshServer.status), pid: numberOrNull(organ.cultMeshServer.pid), bind: stringOrNull(organ.cultMeshServer.bind), storePath: stringOrNull(organ.cultMeshServer.storePath), odinCultMeshUri: stringOrNull(organ.cultMeshServer.odinCultMeshUri), odinRudpEndpoint: stringOrNull(organ.cultMeshServer.odinRudpEndpoint), error: stringOrNull(organ.cultMeshServer.error), } : null, })); } function projectHistoryEvent(event) { return { type: String(event?.type ?? "event"), identityId: stringOrNull(event?.identityId), observedAt: stringOrNull(event?.observedAt ?? event?.queuedAt ?? event?.consumedAt ?? event?.appliedAt), activeJobId: stringOrNull(event?.activeJobId), statusPath: stringOrNull(event?.statusPath), reason: stringOrNull(event?.reason), pendingMentionCount: numberOrNull(event?.pendingMentionCount), mentionCount: numberOrNull(event?.mentionCount), nextTurnAt: numberOrNull(event?.nextTurnAt), recoveryMinutes: numberOrNull(event?.recoveryMinutes), }; } function buildRecentMentionActivity(history, pendingMentions) { const activity = []; for (const mention of pendingMentions ?? []) { const projected = projectPendingMention(mention); activity.push({ kind: "pending", identityId: projected.identityId, sourceChannelId: projected.sourceChannelId, sourceMessageId: projected.sourceMessageId, observedAt: projected.createdAt, mentionCount: 1, prompt: projected.prompt, }); } const events = Array.isArray(history) ? history : []; for (let index = events.length - 1; index >= 0 && activity.length < 16; index -= 1) { const event = events[index]; const type = String(event?.type ?? ""); if (type === "pending_mentions_consumed") { const mentions = Array.isArray(event?.mentions) ? event.mentions.map(projectMentionEventEntry) : []; activity.push({ kind: "consumed", identityId: stringOrNull(event?.identityId), observedAt: stringOrNull(event?.consumedAt ?? event?.queuedAt), activeJobId: stringOrNull(event?.activeJobId), requestMessageId: stringOrNull(event?.requestMessageId), mentionCount: numberOrNull(event?.mentionCount) ?? mentions.length, sourceChannelId: mentions[0]?.sourceChannelId ?? null, sourceMessageId: mentions[0]?.sourceMessageId ?? null, prompt: mentions[0]?.prompt ?? "", mentions, }); } else if (type === "pending_mention_queued" || type === "pending_mention_duplicate") { activity.push({ kind: type === "pending_mention_duplicate" ? "duplicate_intake" : "intake", identityId: stringOrNull(event?.identityId), sourceChannelId: stringOrNull(event?.sourceChannelId ?? event?.channelId), sourceMessageId: stringOrNull(event?.sourceMessageId ?? event?.messageId), observedAt: stringOrNull(event?.queuedAt ?? event?.observedAt), mentionCount: 1, prompt: "", }); } else if ( type === "queued" && typeof event?.pendingMentionCount === "number" && event.pendingMentionCount > 0 ) { activity.push({ kind: "handled_job", identityId: stringOrNull(event?.identityId), observedAt: stringOrNull(event?.queuedAt ?? event?.observedAt), activeJobId: stringOrNull(event?.activeJobId), requestMessageId: stringOrNull(event?.requestMessageId), mentionCount: numberOrNull(event?.pendingMentionCount), prompt: "", }); } } return activity .sort((left, right) => timestampMs(right.observedAt) - timestampMs(left.observedAt)) .slice(0, 12); } function projectMentionEventEntry(mention) { return { id: stringOrNull(mention?.id), sourceChannelId: stringOrNull(mention?.sourceChannelId ?? mention?.channelId), sourceMessageId: stringOrNull(mention?.sourceMessageId ?? mention?.messageId), authorId: stringOrNull(mention?.authorId), authorName: stringOrNull(mention?.authorName), createdAt: stringOrNull(mention?.createdAt ?? mention?.queuedAt), prompt: truncate(String(mention?.prompt ?? mention?.visiblePrompt ?? mention?.content ?? ""), 220), }; } async function readIdentityMetadata(registryPathValue) { const metadata = new Map(); const registryPath = resolveConfigPath(registryPathValue, resolve(repoRoot, ".voidbot", "private", "repo-discord-identities.json")); const registry = await readJsonFile(registryPath); const identities = Array.isArray(registry.value?.identities) ? registry.value.identities : Array.isArray(registry.value) ? registry.value : []; for (const identity of identities) { const id = typeof identity?.id === "string" ? identity.id.toLowerCase() : ""; if (id) { metadata.set(id, { id, displayName: stringOrNull(identity?.displayName), repoName: stringOrNull(identity?.repoName), repoPath: stringOrNull(identity?.repoPath), identityKind: stringOrNull(identity?.identityKind), faceStatePath: stringOrNull(identity?.faceStatePath), personaStatePath: stringOrNull(identity?.personaStatePath), description: stringOrNull(identity?.description), avatarUrl: stringOrNull(identity?.avatarUrl), avatarPath: stringOrNull(identity?.avatarPath), channelPermissions: Array.isArray(identity?.channelPermissions) ? identity.channelPermissions : [], }); } } return metadata; } async function readFaceStates(identityMetadata) { const states = new Map(); let core = null; try { const requireCore = createRequire(resolve(repoRoot, "packages", "core", "package.json")); core = requireCore(resolve(repoRoot, "packages", "core", "dist", "index.js")); } catch (error) { for (const [id, identity] of identityMetadata.entries()) { states.set(id, { readable: false, path: identity.faceStatePath ?? null, error: `Core typed-state loader unavailable: ${error instanceof Error ? error.message : String(error)}`, tree: [], }); } return states; } for (const [id, identity] of identityMetadata.entries()) { if (identity.identityKind === "native_persona") { states.set(id, readPersonaStateSummary(identity)); continue; } if (!identity.faceStatePath) { states.set(id, { readable: false, path: null, error: "No Face state path registered.", tree: [], }); continue; } try { const typedState = await core.loadVoidSelfStateTypedDocuments({ canonicalPath: identity.faceStatePath, identity: { agentId: id, publicName: identity.displayName ?? id, publicDescription: identity.description ?? undefined, }, }); const rendered = core.buildVoidSelfStateContext ? core.buildVoidSelfStateContext(typedState, { sourcePath: identity.faceStatePath, identity: { agentId: id, publicName: identity.displayName ?? id, publicDescription: identity.description ?? undefined, }, }) : null; states.set(id, { readable: true, path: identity.faceStatePath, summary: truncate(rendered?.summary ?? "", 1200), counts: countFaceState(typedState), restState: projectRestState(typedState), tree: buildFaceStateTree(typedState), }); } catch (error) { states.set(id, { readable: false, path: identity.faceStatePath, error: error instanceof Error ? error.message : String(error), tree: [], }); } } return states; } function readPersonaStateSummary(identity) { if (!identity.personaStatePath) { return { readable: false, path: null, error: "No Persona state path registered.", tree: [], }; } try { const raw = readFileSync(resolve(identity.personaStatePath), "utf8"); const state = JSON.parse(stripBom(raw)); return { readable: true, kind: "native_persona", path: identity.personaStatePath, summary: truncate(state.publicDescription ?? state.presentation?.voiceSummary ?? "", 1200), counts: { memory: state.thoughtMemory?.memories?.length ?? 0, pressures: state.agencyPressure?.pressures?.length ?? 0, needs: state.affect?.needs?.length ?? 0, statusReads: state.affect?.statusReads?.length ?? 0, doctrine: state.affect?.doctrineStances?.length ?? 0, }, tree: buildPersonaStateTree(state), }; } catch (error) { return { readable: false, kind: "native_persona", path: identity.personaStatePath, error: error instanceof Error ? error.message : String(error), tree: [], }; } } function buildPersonaStateTree(state) { return [ node("Persona", "persona", [ leaf("Public Name", state.publicName), leaf("Description", state.publicDescription), leaf("Voice", state.presentation?.voiceSummary), collectionNode("Values", "values", state.values, valueNode), objectNode("Activation", "activationProfile", state.activationProfile), collectionNode("Private Notes", "privateNotes", state.privateNotes, valueNode), ]), node("Thought Memory", "thoughtMemory", [ collectionNode("Short Term", "thoughtMemory.shortTerm", state.thoughtMemory?.shortTerm, memoryNode), collectionNode("Durable Memories", "thoughtMemory.memories", state.thoughtMemory?.memories, memoryNode), collectionNode("Incubation", "thoughtMemory.incubation", state.thoughtMemory?.incubation, memoryNode), ]), node("Affect", "affect", [ collectionNode("Needs", "affect.needs", state.affect?.needs, valueNode), collectionNode("Status Reads", "affect.statusReads", state.affect?.statusReads, valueNode), collectionNode("Doctrine", "affect.doctrineStances", state.affect?.doctrineStances, valueNode), ]), ]; } function projectRestState(typedState) { const sleepCycle = typedState?.scheduledRuntime?.sleepCycle; if (!sleepCycle || typeof sleepCycle !== "object") { return null; } return { isNapping: sleepCycle.isNapping === true, napEndsAt: stringOrNull(sleepCycle.currentNapEndsAt), nextNapStartsAt: stringOrNull(sleepCycle.nextNapStartsAt), activeDreamThemes: Array.isArray(sleepCycle.activeDreamThemes) ? sleepCycle.activeDreamThemes.slice(0, 8).map(String) : [], }; } function countFaceState(typedState) { return { shortTerm: typedState?.thoughtMemory?.shortTerm?.length ?? 0, memories: typedState?.thoughtMemory?.memories?.length ?? 0, incubation: typedState?.thoughtMemory?.incubation?.length ?? 0, bonds: typedState?.faceAffect?.socialBonds?.length ?? 0, pressures: typedState?.agencyPressure?.pressures?.length ?? 0, candidates: typedState?.candidateInterventions?.interventions?.length ?? 0, }; } function buildFaceStateTree(typedState) { return [ node("Self Profile", "selfProfile", [ leaf("Public Name", typedState?.selfProfile?.publicName), leaf("Description", typedState?.selfProfile?.publicDescription), collectionNode("Values", "selfProfile.values", typedState?.selfProfile?.values, valueNode), objectNode("Activation", "selfProfile.activationProfile", typedState?.selfProfile?.activationProfile), collectionNode("Private Notes", "selfProfile.privateNotes", typedState?.selfProfile?.privateNotes, valueNode), ]), node("Thought Memory", "thoughtMemory", [ collectionNode("Short Term", "thoughtMemory.shortTerm", typedState?.thoughtMemory?.shortTerm, memoryNode), collectionNode("Durable Memories", "thoughtMemory.memories", typedState?.thoughtMemory?.memories, memoryNode), collectionNode("Incubation", "thoughtMemory.incubation", typedState?.thoughtMemory?.incubation, memoryNode), ]), node("Affect", "faceAffect", [ collectionNode("Needs", "faceAffect.needs", typedState?.faceAffect?.needs, valueNode), collectionNode("Social Bonds", "faceAffect.socialBonds", typedState?.faceAffect?.socialBonds, memoryNode), collectionNode("Status Reads", "faceAffect.statusReads", typedState?.faceAffect?.statusReads, memoryNode), objectNode("Mood", "faceAffect.moodDimensions", typedState?.faceAffect?.moodDimensions), collectionNode("Social Biases", "faceAffect.socialBiases", typedState?.faceAffect?.socialBiases, valueNode), ]), node("Agency", "agencyPressure", [ collectionNode("Pressures", "agencyPressure.pressures", typedState?.agencyPressure?.pressures, memoryNode), collectionNode("Candidates", "candidateInterventions.interventions", typedState?.candidateInterventions?.interventions, memoryNode), ]), node("Runtime", "scheduledRuntime", [ objectNode("Sleep Cycle", "scheduledRuntime.sleepCycle", typedState?.scheduledRuntime?.sleepCycle), objectNode("Speaking Pressure", "scheduledRuntime.speakingPressure", typedState?.scheduledRuntime?.speakingPressure), objectNode("Last Runs", "scheduledRuntime.lastRuns", typedState?.scheduledRuntime?.lastRuns), ]), ].filter(Boolean); } function node(label, path, children = []) { const compactChildren = children.filter(Boolean); return { kind: "branch", label, path, children: compactChildren, count: compactChildren.length }; } function leaf(label, value, path = label) { if (value === null || value === undefined || value === "") return null; return { kind: "leaf", label, path, title: label, preview: truncate(renderValuePreview(value), 120), detail: renderValueDetail(value), }; } function collectionNode(label, path, values, projector) { if (!Array.isArray(values) || values.length === 0) return node(label, path, [leaf("empty", "No entries.", `${path}.empty`)]); return node(label, path, values.slice(0, 80).map((value, index) => projector(value, `${path}.${index}`, index))); } function objectNode(label, path, value) { if (!value || typeof value !== "object") return node(label, path, [leaf("empty", "No entries.", `${path}.empty`)]); const children = Object.entries(value).slice(0, 80).map(([key, entry]) => { if (entry && typeof entry === "object") return objectNode(key, `${path}.${key}`, entry); return leaf(key, entry, `${path}.${key}`); }); return node(label, path, children); } function valueNode(value, path, index) { if (value && typeof value === "object") { const title = value.label ?? value.name ?? value.kind ?? value.id ?? `entry ${index + 1}`; return leaf(String(title), value, path); } return leaf(`entry ${index + 1}`, value, path); } function memoryNode(value, path, index) { if (!value || typeof value !== "object") return leaf(`entry ${index + 1}`, value, path); const target = value.target?.label ?? value.target?.id ?? value.targetKind ?? value.target ?? value.kind; const title = value.summary ?? value.claim ?? value.question ?? value.title ?? value.id ?? value.memoryId ?? `entry ${index + 1}`; const label = target ? `${target}: ${title}` : title; return { kind: "leaf", label: truncate(String(label), 120), path, title: String(title), preview: truncate(value.claim ?? value.question ?? value.tension ?? value.actionImplication ?? value.summary ?? renderValuePreview(value), 180), detail: renderMemoryDetail(value), }; } function renderMemoryDetail(value) { const lines = []; for (const key of ["kind", "summary", "claim", "question", "tension", "actionImplication", "status", "intensity", "createdAt", "updatedAt"]) { if (value?.[key] !== null && value?.[key] !== undefined && value?.[key] !== "") { lines.push(`${key}: ${renderValuePreview(value[key])}`); } } if (value?.target) lines.push(`target: ${renderValuePreview(value.target)}`); if (Array.isArray(value?.anchorRefs) && value.anchorRefs.length > 0) { lines.push(`anchors:\n${value.anchorRefs.map((anchor) => `- ${renderValuePreview(anchor)}`).join("\n")}`); } if (Array.isArray(value?.tags) && value.tags.length > 0) lines.push(`tags: ${value.tags.join(", ")}`); return lines.join("\n\n") || renderValueDetail(value); } function renderValuePreview(value) { if (typeof value === "string") return value; if (typeof value === "number" || typeof value === "boolean") return String(value); return JSON.stringify(value); } function renderValueDetail(value) { return typeof value === "string" ? value : JSON.stringify(value, null, 2); } function projectPendingMention(mention) { return { identityId: stringOrNull(mention?.identityId), sourceChannelId: stringOrNull(mention?.sourceChannelId ?? mention?.channelId), sourceMessageId: stringOrNull(mention?.sourceMessageId ?? mention?.messageId), createdAt: stringOrNull(mention?.createdAt ?? mention?.queuedAt), prompt: truncate(String(mention?.prompt ?? mention?.visiblePrompt ?? mention?.content ?? ""), 220), }; } function deriveSwarmState({ heartbeat, orchestrator, paused, activeTurns }) { if (!heartbeat.ok) return "missing"; if (paused) return "paused"; const organ = projectOrgans(orchestrator.value).find((entry) => entry.id === "repo-face-heartbeats"); if (organ && organ.lastStatus && !["ok", "skipped_disabled"].includes(organ.lastStatus)) { return "warning"; } if (activeTurns.length > 0) return "running"; return "ready"; } function deriveOrchestratorState(organs) { if (organs.length === 0) return "missing"; if (organs.some((organ) => ["failed", "error", "stalled"].includes(organ.lastStatus))) return "warning"; if (organs.some((organ) => organ.lastStatus === "running")) return "running"; return "ok"; } async function writeCultMeshPublication(snapshot, eveState, storePath, allowStoreReset = true) { try { const cultPackages = loadCultPackages(); if (!cultPackages) { return { writeStatus: "skipped", writeError: "CultMesh/CultCache packages were not found in known local CultLib paths.", }; } const { CultMesh, defineDocumentType } = cultPackages; const snapshotDefinition = defineDocumentType({ type: snapshotDocumentType, schemaName: snapshotDocumentType, schemaId: snapshotSchemaId, schemaVersion: snapshotSchemaId, contentHash: snapshotSchemaId, canonicalSchemaJson: JSON.stringify({ schemaName: snapshotDocumentType, schemaVersion: snapshotSchemaId, description: "Redacted read-only VoidBot swarm state snapshot for CultMesh distribution.", }), global: true, schema: { parse(input) { if (!input || typeof input !== "object") { throw new Error("VoidBot swarm snapshot must be an object."); } return input; }, }, }); const providerDefinition = defineDocumentType({ type: providerAdvertisementDocumentType, schemaName: providerAdvertisementDocumentType, schemaId: providerAdvertisementSchemaId, schemaVersion: providerAdvertisementSchemaId, contentHash: providerAdvertisementSchemaId, global: false, name: "providerId", schema: { parse: parseObjectDocument("Eve provider advertisement") }, }); const surfaceDefinition = defineDocumentType({ type: surfaceDocumentType, schemaName: surfaceDocumentType, schemaId: surfaceSchemaId, schemaVersion: surfaceSchemaId, contentHash: surfaceSchemaId, global: false, name: "providerId", schema: { parse: parseObjectDocument("Eve surface state") }, }); const eveBindingDefinition = defineDocumentType({ type: eveBindingDocumentType, schemaName: eveBindingDocumentType, schemaId: eveBindingSchemaId, schemaVersion: eveBindingSchemaId, contentHash: eveBindingSchemaId, global: false, name: "bindingId", schema: { parse: parseObjectDocument("Eve interface binding") }, }); const providerCatalogDefinition = defineDocumentType({ type: providerCatalogDocumentType, schemaName: providerCatalogDocumentType, schemaId: providerCatalogSchemaId, schemaVersion: providerCatalogSchemaId, contentHash: providerCatalogSchemaId, global: true, schema: { parse: parseObjectDocument("VoidBot provider advertisement catalog") }, }); const transportProfileDefinition = defineDocumentType({ type: transportProfileDocumentType, schemaName: transportProfileDocumentType, schemaId: transportProfileSchemaId, schemaVersion: transportProfileSchemaId, contentHash: transportProfileSchemaId, global: false, name: (value) => value?.profile_id || value?.daemon_id || "voidbot", schema: { parse: parseObjectDocument("Idunn daemon transport profile") }, }); const commandBoundaryDefinition = defineDocumentType({ type: commandBoundaryDocumentType, schemaName: commandBoundaryDocumentType, schemaId: commandBoundarySchemaId, schemaVersion: commandBoundarySchemaId, contentHash: commandBoundarySchemaId, global: false, name: (value) => value?.boundary_id || value?.daemon_id || "voidbot", schema: { parse: parseObjectDocument("Idunn command boundary") }, }); const swarmControlDefinition = defineDocumentType({ type: swarmControlDocumentType, schemaName: swarmControlDocumentType, schemaId: swarmControlSchemaId, schemaVersion: swarmControlSchemaId, contentHash: swarmControlSchemaId, global: false, name: () => "voidbot-swarm", schema: { parse: parseObjectDocument("VoidBot swarm control state") }, }); const node = await CultMesh.createNode(storePath, { documents: [ snapshotDefinition, providerDefinition, surfaceDefinition, eveBindingDefinition, providerCatalogDefinition, transportProfileDefinition, commandBoundaryDefinition, swarmControlDefinition, ], }); const providerCatalog = loadProviderAdvertisementCatalog(snapshot); const providerAdvertisements = buildLiveProviderAdvertisements(providerCatalog, snapshot); const providerAdvertisement = providerAdvertisements.find((item) => item.providerId === providerId) ?? buildProviderAdvertisement(snapshot); const eveBinding = buildEveInterfaceBinding(snapshot, eveState); const commandBoundary = buildCommandBoundary(snapshot); const transportProfile = buildTransportProfile(snapshot); await node.put(snapshotDefinition, "voidbot-swarm", snapshot); await node.put(providerCatalogDefinition, "voidbot.providers", providerCatalog); for (const advertisement of providerAdvertisements) { await node.put(providerDefinition, advertisement.providerId, advertisement); } await node.put(surfaceDefinition, providerId, eveState); await node.put(eveBindingDefinition, providerId, eveBinding); await node.put(commandBoundaryDefinition, commandBoundary.boundary_id, commandBoundary); await node.put(transportProfileDefinition, transportProfile.profile_id, transportProfile); await node.flush?.(true); return { writeStatus: "ok", storePath, documents: [ snapshotDocumentType, providerCatalogDocumentType, providerAdvertisementDocumentType, surfaceDocumentType, eveBindingDocumentType, commandBoundaryDocumentType, transportProfileDocumentType, ], providerId, verseId, eveBinding: { documentType: eveBindingDocumentType, schemaId: eveBindingSchemaId, key: providerId, }, eveDeckEndpoint: primaryCultMeshEndpoint(), writtenAt: new Date().toISOString(), }; } catch (error) { const message = error instanceof Error ? error.message : String(error); if ( allowStoreReset && existsSync(storePath) && /global document type .* has multiple persisted entries/i.test(message) ) { const backupPath = `${storePath}.bak-duplicate-globals-${timestampForFile(new Date())}`; await rename(storePath, backupPath); const retry = await writeCultMeshPublication(snapshot, eveState, storePath, false); return { ...retry, recoveredFrom: { reason: "duplicate-global-documents", backupPath, }, }; } return { writeStatus: "failed", storePath, writeError: message, }; } } function timestampForFile(date) { return date.toISOString().replace(/[:.]/g, "").replace("T", "-").replace("Z", "Z"); } function loadCultPackages() { const cultLibRoot = process.env.VOIDBOT_CULTLIB_ROOT ? resolve(process.env.VOIDBOT_CULTLIB_ROOT) : resolve(repoRoot, "..", "CultLib-dev-runtime"); const candidates = [ resolve(cultLibRoot, "packages", "cultmesh-ts", "package.json"), resolve(repoRoot, "..", "CultMeshTS", "package.json"), ]; for (const packageJson of candidates) { if (!existsSync(packageJson)) { continue; } try { const requireCult = createRequire(packageJson); const { CultMesh } = requireFirstAvailable(requireCult, [ "cultmesh-ts", "cultmesh-ts/dist/index.js", ]); const { defineDocumentType } = requireFirstAvailable(requireCult, [ "cultcache-ts", "cultcache-ts/dist/index.js", ]); if (CultMesh && defineDocumentType) { return { CultMesh, defineDocumentType }; } } catch { continue; } } return null; } function requireFirstAvailable(requireFromPackage, specifiers) { let lastError; for (const specifier of specifiers) { try { return requireFromPackage(specifier); } catch (error) { lastError = error; } } throw lastError; } function parseObjectDocument(label) { return (input) => { if (!input || typeof input !== "object") { throw new Error(`${label} must be an object.`); } return input; }; } function loadProviderAdvertisementCatalog(snapshot) { const fixturePath = resolve(repoRoot, "docs", "architecture", "voidbot-provider-advertisements.fixture.json"); const fixture = JSON.parse(readFileSync(fixturePath, "utf8")); fixture.fixtureKind = "daemon-live-publication"; fixture.generatedAt = snapshot.generatedAt; fixture.cultMeshKeys.liveSwarmStore = cultMeshStorePath; return fixture; } function buildLiveProviderAdvertisements(catalog, snapshot) { const providers = Array.isArray(catalog.providers) ? catalog.providers : []; return providers.map((provider) => { if (provider.providerId === providerId) { return { ...provider, status: snapshot.summary?.state ?? provider.status ?? "unknown", updatedAt: snapshot.generatedAt, endpoints: providerEndpoints(), routes: providerRoutes(), cultMeshAddress: primaryCultMeshEndpoint(), witnesses: Array.isArray(provider.witnesses) ? provider.witnesses.map((witness) => witness.id === "voidbot.swarm_state_snapshot" ? { ...witness, path: cultMeshStorePath } : witness) : provider.witnesses, }; } return { ...provider, updatedAt: snapshot.generatedAt, }; }); } function buildProviderAdvertisement(snapshot) { const endpoints = providerEndpoints(); return { schemaVersion: providerAdvertisementSchemaId, providerId, verseId, title: "VoidBot Swarm", description: "VoidBot swarm status, CTB order, controls, and selected Face state as an Eve/CultUI surface.", version: String(snapshot.summary?.initiativeClock ?? Date.now()), status: snapshot.summary?.state ?? "unknown", updatedAt: snapshot.generatedAt, endpoints, routes: providerRoutes(), cultMeshAddress: primaryCultMeshEndpoint(), provider: providerManifest(), controlSurface: { primary: primaryCultMeshEndpoint(), controls: { transport: "cultmesh-binding", documentType: eveBindingDocumentType, key: providerId, }, }, documents: [{ type: snapshotDocumentType, schemaId: snapshotSchemaId, key: "voidbot-swarm", }, { type: surfaceDocumentType, schemaId: surfaceSchemaId, key: providerId, }, { type: eveBindingDocumentType, schemaId: eveBindingSchemaId, key: providerId, }], }; } function buildCommandBoundary(snapshot) { return { boundary_id: "command-boundary:voidbot", daemon_id: "voidbot", owner: "VoidBot local stack", restart_authority: "E:\\Projects\\Odin\\scripts\\restart-voidbot.cmd", deploy_authority: "none", health_authority: "voidbot.cultnet-rudp-stack-health", alarm_authority: "bifrost.operator-notification", command_lowerings: [ "E:\\Projects\\Odin\\scripts\\restart-voidbot.cmd", ], forbidden_authority: "Health commands, operations watchdog probes, static HTML lowerings, and Odin renderers do not own VoidBot provider state or restart truth.", observed_at: snapshot.generatedAt, }; } function buildTransportProfile(snapshot) { return { profile_id: "transport:voidbot", daemon_id: "voidbot", target_transport: "cultnet.transport.rudp.v0", current_transport: "daemon-published-rudp-health + daemon-owned-cultmesh-rudp-provider", state: "rudp-health-and-provider-cultmesh-live", health_contract: "voidbot.cultnet-rudp-stack-health", publication_schema: "gamecult.eve.provider_advertisement.v1 + idunn.command_boundary.v1 + idunn.daemon_transport_profile.v1", debug_mechanism: "operations-health.json debug witness only", provider_document_route: swarmCultMeshRudpEndpoint, cut_line: `VoidBot publishes provider advertisements, command boundary, transport profile, and Eve surface through ${primaryCultMeshEndpoint()} with direct CultMesh/RUDP document route ${swarmCultMeshRudpEndpoint}; local probes do not own daemon health or provider transport.`, observed_at: snapshot.generatedAt, }; } function buildEveInterfaceBinding(snapshot, eveState) { return { schemaVersion: eveBindingSchemaId, bindingId: providerId, providerId, verseId, title: "VoidBot Swarm", kind: "eve-cultui-surface", updatedAt: snapshot.generatedAt, authority: { owner: "VoidBot swarm renderer", sourceDocuments: [{ type: snapshotDocumentType, schemaId: snapshotSchemaId, key: "voidbot-swarm", }], surfaceDocument: { type: surfaceDocumentType, schemaId: surfaceSchemaId, key: providerId, }, controlOwner: "VoidBot heartbeat state", }, surface: eveState.surface, stateSummary: { state: snapshot.summary?.state ?? "unknown", participantCount: snapshot.summary?.participantCount ?? 0, activeTurnCount: snapshot.summary?.activeTurnCount ?? 0, pendingMentionCount: snapshot.summary?.pendingMentionCount ?? 0, recentMentionActivityCount: snapshot.summary?.recentMentionActivityCount ?? 0, lastMentionActivity: snapshot.summary?.lastMentionActivity ?? null, nextIdentityId: snapshot.summary?.nextIdentityId ?? null, nextDisplayName: snapshot.summary?.nextDisplayName ?? null, lastTickAt: snapshot.summary?.lastTickAt ?? null, }, controls: [{ id: "swarm.pause", label: "Pause swarm", command: "set-pause", writes: { documentType: eveBindingDocumentType, key: providerId, field: "controlIntent.pause", }, }, { id: "swarm.heat", label: "Set heat", command: "set-heat", writes: { documentType: eveBindingDocumentType, key: providerId, field: "controlIntent.globalHeat", }, }, { id: "swarm.cadence", label: "Set cadence", command: "set-cadence-multiplier", writes: { documentType: eveBindingDocumentType, key: providerId, field: "controlIntent.cadenceMultiplier", }, }, { id: "swarm.force-turn", label: "Pull Face forward", command: "force-turn", writes: { documentType: eveBindingDocumentType, key: providerId, field: "controlIntent.manualTurnRequests", }, }], rendererHints: { preferredLowerings: ["eve-native", "nightwing-tui", "browser"], viewportMode: "continuous-ops", tileId: "voidbot-swarm", minWidth: 112, minHeight: 30, preferredWidth: 156, preferredHeight: 58, priority: -30, density: "continuous", }, lowerings: [{ kind: "static-html", role: "local-debug-artifact", path: dashboardPath, }], }; } function providerManifest() { return { id: providerId, title: "VoidBot Swarm", description: "Native Eve tab for VoidBot agent status, CTB order, selected Face state, and swarm controls.", version: "1", endpoint: primaryCultMeshEndpoint(), capabilities: ["ctb", "agent-status", "state-tree", "swarm-controls", "cultmesh-snapshot"], usesCultMesh: true, transport: "CultMesh Eve interface binding.", }; } function buildEveProviderState(snapshot) { const operatorBinding = (targetProp, pointerId) => ({ targetProp, pointerId, sourceId: "voidbot.swarm_operator_view:voidbot-swarm", schemaId: "voidbot.swarm_operator_view.v1", routeKind: "cultmesh-rudp", routeDescription: swarmCultMeshRudpEndpoint, }); const summary = snapshot.summary ?? {}; const participants = Array.isArray(snapshot.participants) ? snapshot.participants : []; const upcoming = Array.isArray(snapshot.upcomingTurns) ? snapshot.upcomingTurns : []; const activeTurns = Array.isArray(snapshot.activeTurns) ? snapshot.activeTurns : []; const pendingMentions = Array.isArray(snapshot.pendingMentions) ? snapshot.pendingMentions : []; const recentMentionActivity = Array.isArray(snapshot.recentMentionActivity) ? snapshot.recentMentionActivity : []; const recentEvents = Array.isArray(snapshot.recentEvents) ? snapshot.recentEvents : []; const orchestrator = snapshot.orchestrator ?? {}; const organs = Array.isArray(orchestrator.organs) ? orchestrator.organs : []; const watchdog = findSnapshotOrgan(organs, "voidbot-operations-watchdog") ?? findSnapshotOrgan(organs, "watchdog"); const repoFaceOrgan = findSnapshotOrgan(organs, "repo-face-heartbeats"); const swarmSurfaceOrgan = findSnapshotOrgan(organs, "voidbot-swarm-surface"); const selected = selectDashboardParticipant(snapshot, participants, upcoming); const selectedLeaf = findDashboardLeaf(selected); const counts = selected?.faceState?.counts ?? {}; const memoryCount = (counts.shortTerm ?? 0) + (counts.memories ?? 0) + (counts.incubation ?? 0); const pressureCount = counts.pressures ?? 0; const highPressureFaces = [...participants] .sort(compareOperatorPressure) .slice(0, 6); const liveQueue = [ ...activeTurns.map((turn) => ({ ...turn, operatorState: "active" })), ...upcoming.filter((turn) => (turn.nextTurnInMinutes ?? 999999) <= 20).map((turn) => ({ ...turn, operatorState: turn.nextTurnInMinutes <= 0 ? "ready" : "soon", })), ].filter((turn, index, all) => index === all.findIndex((entry) => entry.identityId === turn.identityId) ).slice(0, 6); const route = routeSummary(snapshot, swarmSurfaceOrgan); const operatorAlerts = buildOperatorAlerts(snapshot, { watchdog, repoFaceOrgan, swarmSurfaceOrgan, pendingMentions, recentMentionActivity, activeTurns, }); const nodes = [ { id: "voidbot-swarm", label: `VoidBot Swarm\n${summary.state ?? "unknown"}`, kind: "cultmesh-verse", visible: true, health: summary.state ?? "unknown", detail: `agents ${summary.participantCount ?? participants.length}; next ${summary.nextDisplayName ?? "none"}`, }, ...participants.slice(0, 24).map((participant, index) => ({ id: `face-${participant.identityId}`, label: `${participant.displayName}\n${participant.repoName}`, kind: "repo-face", visible: true, x: -0.9 + (index % 6) * 0.36, y: -0.3 + Math.floor(index / 6) * 0.22, z: 0, rotation: 0, scale: 1, width: 0.26, height: 0.16, health: participant.activeJobId ? "running" : participant.restState?.isNapping ? "napping" : participant.status, detail: `next ${participant.nextTurnInMinutes ?? "?"}m; heat ${participant.heat ?? "?"}`, })), ]; return { type: "dashboard-state", schema: "mimir.eve_dashboard_state.v1", providerId, title: "VoidBot Swarm", version: Math.floor(Date.parse(snapshot.generatedAt ?? new Date().toISOString()) / 1000), updatedAt: snapshot.generatedAt, selectedNodeId: "voidbot-swarm", lutPreset: "terminal", nodes, surface: { schema: "gamecult.eve.surface.v1", id: "voidbot.swarm.surface", title: "VoidBot Swarm", styles: { tokens: { colorBackground: "#03070d", colorBackgroundTop: "#02060b", colorBackgroundMid: "#06100f", colorBackgroundBottom: "#08130f", colorPanel: "rgba(6, 15, 19, 0.92)", colorPanelAlt: "rgba(10, 36, 35, 0.96)", colorPanelBorder: "rgba(142, 223, 176, 0.22)", colorPanelBorderDeep: "rgba(142, 223, 176, 0.15)", colorText: "#e8f3ee", colorMuted: "#8fa79d", colorAccent: "#ffae58", colorAccentStrong: "#8efcff", colorLink: "#8efcff", fontMono: "\"Cascadia Mono\", Consolas, monospace", }, }, root: eveNode("voidbot-cockpit", "cockpit", { title: "VoidBot Swarm", status: summary.state ?? "unknown", layout: { direction: "vertical", overflowX: "hidden", overflowY: "auto", gap: 8, padding: 8, grow: 5, minWidth: 112, minHeight: 30, preferredWidth: 156, preferredHeight: 58, priority: -30, density: "continuous", viewportMode: "continuous-ops", }, }, [ eveNode("ctb-command-row", "row", { layout: { direction: "horizontal", gap: 8, alignItems: "stretch", overflowX: "hidden" }, }, [ eveNode("ctb-rail", "rail", { title: "CTB order", layout: { direction: "horizontal", overflow: "hidden", height: 96, gap: 6, padding: 6, grow: 1 }, }, upcoming.slice(0, 8).map((turn, index) => eveNode(`turn-${stableId(turn.identityId)}-${index}`, "avatar", { text: turn.displayName, assetUri: turn.avatarUrl, status: turnState(turn), detail: `${turn.repoName ?? "repo"} / ${minutesText(turn.nextTurnInMinutes)}`, }), )), eveNode("swarm-heat-control", "pane", { title: "Heat", density: "compact", layout: { width: 220, minWidth: 220 } }, [ eveNode("swarm-heat-value", "text", { role: "mono", text: "loading", stateBindings: [{ targetProp: "text", pointerId: "globalHeat", sourceId: "voidbot.swarm_control_state:voidbot-swarm", schemaId: "voidbot.swarm_control_state.v1", routeKind: "cultmesh-rudp", routeDescription: swarmCultMeshRudpEndpoint, }], }), eveNode("swarm-heat-scale", "text", { role: "caption", text: "low 0.05 · nominal 1.00 · hot 2.00", }), eveNode("swarm-heat-slider", "control.slider", { label: "Swarm heat", bind: "voidbot.swarm.globalHeat", command: "swarm.set_heat", transport: "cultmesh-binding", providerId, min: 0.05, max: 2, step: 0.05, stateBindings: [{ targetProp: "value", pointerId: "globalHeat", sourceId: "voidbot.swarm_control_state:voidbot-swarm", schemaId: "voidbot.swarm_control_state.v1", routeKind: "cultmesh-rudp", routeDescription: swarmCultMeshRudpEndpoint, }], }), ]), ]), eveNode("voidbot-status-metrics", "row", { layout: { direction: "horizontal", gap: 8 } }, [ eveNode("metric-swarm-state", "metric", { label: "Swarm", value: summary.state ?? "unknown", stateBindings: [operatorBinding("value", "summary.state")] }), eveNode("metric-participants", "metric", { label: "Faces", value: summary.participantCount ?? participants.length, stateBindings: [operatorBinding("value", "summary.participantCount")] }), eveNode("metric-active-turns", "metric", { label: "Active", value: activeTurns.length || summary.activeTurnCount || 0, stateBindings: [operatorBinding("value", "summary.activeTurnCount")] }), eveNode("metric-ready-now", "metric", { label: "Ready", value: summary.readyNowCount ?? 0, stateBindings: [operatorBinding("value", "summary.readyNowCount")] }), eveNode("metric-pending-mentions", "metric", { label: "Mentions", value: summary.pendingMentionCount ?? 0, stateBindings: [operatorBinding("value", "summary.pendingMentionCount")] }), ]), eveNode("voidbot-operator-deck", "grid", { columns: "minmax(260px, 0.95fr) minmax(320px, 1.15fr) minmax(280px, 1fr) minmax(260px, 0.9fr)", layout: { gap: 8, alignItems: "stretch" }, }, [ eveNode("voidbot-inspector", "pane", { title: "Selected Face", density: "compact" }, selected ? [ eveNode(`selected-avatar-${stableId(selected.identityId)}`, "avatar", { text: selected.displayName, assetUri: selected.avatarUrl, status: selected.activeJobId ? "active" : selected.restState?.isNapping ? "napping" : selected.status, detail: `${selected.identityId} / ${selected.repoName}`, stateBindings: [ operatorBinding("text", "selectedFace.displayName"), operatorBinding("assetUri", "selectedFace.avatarUri"), operatorBinding("status", "selectedFace.status"), operatorBinding("detail", "selectedFace.repoName"), ], }), eveNode("metric-selected-turn", "metric", { label: "Turn (min)", value: minutesText(selected.nextTurnInMinutes), stateBindings: [operatorBinding("value", "selectedFace.nextTurnInMinutes")] }), eveNode("metric-selected-memory", "metric", { label: "Memory", value: String(memoryCount), stateBindings: [operatorBinding("value", "selectedFace.memoryCount")] }), eveNode("metric-selected-pressure", "metric", { label: "Pressure", value: String(pressureCount), stateBindings: [operatorBinding("value", "selectedFace.pressureCount")] }), eveNode("selected-description", "text", { role: "caption", text: compactText(selected.description ?? "No Face description registered.", 210), stateBindings: [operatorBinding("text", "selectedFace.description")], }), ] : [ eveNode("selected-missing", "text", { text: "No selected Face." }), ]), eveNode("voidbot-live-queue", "pane", { title: "Live Queue", density: "compact" }, [ eveNode("live-queue-items", "list", { items: [], stateBindings: [operatorBinding("items", "queue")] }), ]), eveNode("voidbot-route-pane", "pane", { title: "CultMesh Route", density: "compact" }, [ eveNode("metric-route-store", "metric", { label: "Store", value: snapshot.cultMesh?.writeStatus ?? "pending", stateBindings: [operatorBinding("value", "route.storeWriteStatus")] }), eveNode("metric-route-provider", "metric", { label: "Provider", value: route.serverStatus, stateBindings: [operatorBinding("value", "route.providerStatus")] }), eveNode("metric-route-odin", "metric", { label: "Odin", value: route.odinStatus, stateBindings: [operatorBinding("value", "route.odinStatus")] }), eveNode("route-alerts", "list", { items: [], stateBindings: [operatorBinding("items", "route.alerts")] }), ]), eveNode("voidbot-controls", "pane", { title: "Controls", density: "compact" }, [ eveNode("metric-swarm-brake", "metric", { label: "Brake", value: summary.paused ? "paused" : "open", stateBindings: [operatorBinding("value", "summary.paused")] }), eveNode("metric-next-face", "metric", { label: "Next", value: summary.nextDisplayName ?? "none", stateBindings: [operatorBinding("value", "summary.nextDisplayName")] }), eveNode("swarm-command-surface", "control.button", { label: summary.paused ? "Request unpause intent" : "Request pause intent", command: summary.paused ? "swarm.unpause.intent" : "swarm.pause.intent", transport: "cultmesh-binding", providerId, }), eveNode("swarm-manual-turn", "control.button", { label: `Request ${summary.nextDisplayName ?? "next Face"}`, command: "swarm.manual_turn.intent", transport: "cultmesh-binding", identityId: summary.nextIdentityId ?? null, }), ]), ]), eveNode("voidbot-detail-deck", "grid", { columns: "minmax(280px, 0.95fr) minmax(320px, 1.05fr) minmax(280px, 1fr) minmax(260px, 0.9fr)", layout: { gap: 8 }, }, [ eveNode("voidbot-state", "pane", { title: "State Detail", density: "compact" }, selectedLeaf ? [ eveNode("state-path", "text", { role: "mono", text: selectedLeaf.path ?? "state path" }), eveNode("state-preview", "text", { role: "mono", text: compactText(selectedLeaf.detail ?? selectedLeaf.preview ?? "", 520) }), ] : [ eveNode("state-empty", "text", { text: selected?.faceState?.error ?? "No readable Face state leaf." }), ]), eveNode("voidbot-watchdog-pane", "pane", { title: "Operations", density: "compact" }, [ eveNode("watchdog-summary", "text", { role: "mono", text: `orchestrator ${orchestrator.state ?? "unknown"} organs ${organs.length}\nmesh ${snapshot.cultMesh?.writeStatus ?? "pending"} ${shortIso(snapshot.cultMesh?.writtenAt ?? snapshot.generatedAt)}`, }), eveBar("watchdog", "Watchdog", watchdog?.lastStatus ?? "missing", statusFill(watchdog?.lastStatus)), eveBar("repo-face-organ", "Faces", repoFaceOrgan?.lastStatus ?? "missing", statusFill(repoFaceOrgan?.lastStatus)), eveBar("swarm-surface-organ", "Eve surface", swarmSurfaceOrgan?.lastStatus ?? "missing", statusFill(swarmSurfaceOrgan?.lastStatus)), ...organs .slice() .sort((left, right) => String(left.id ?? "").localeCompare(String(right.id ?? ""))) .slice(0, 5) .map((organ) => eveNode(`watchdog-organ-${stableId(organ.id)}`, "text", { role: "caption", text: `${organ.label ?? organ.id ?? "organ"}: ${organ.lastStatus ?? "unknown"} / exit ${organ.lastExitCode ?? "?"}`, })), ]), eveNode("voidbot-pressure-pane", "pane", { title: "Pressure", density: "compact" }, highPressureFaces.map((face, index) => eveNode(`pressure-face-${index}-${stableId(face.identityId)}`, "text", { role: "mono", text: `${String(index + 1).padStart(2, " ")} ${String(face.displayName ?? face.identityId ?? "face").padEnd(14, " ")} mem ${String(faceMemoryCount(face)).padStart(2, " ")} prs ${String(facePressureCount(face)).padStart(2, " ")} heat ${formatNumber(face.heat, 2)} q ${face.queuedCount ?? 0}`, }), )), eveNode("pending-mentions-pane", "pane", { title: "Mentions + Events", density: "compact" }, [ ...(pendingMentions.length ? pendingMentions.slice(0, 4).map((mention, index) => eveNode(`pending-mention-${index}`, "text", { role: "mono", text: `${mention.identityId ?? "face"} / ${shortIso(mention.createdAt)}\n${compactText(mention.prompt ?? "", 150)}`, })) : [eveNode("pending-mentions-empty", "text", { text: mentionEmptyText(summary, recentMentionActivity) })]), ...recentMentionActivity.slice(0, 5).map((activity, index) => eveNode(`recent-mention-activity-${index}`, "text", { role: "mono", text: mentionActivityText(activity), }), ), ...recentEvents.slice(0, 4).map((event, index) => eveNode(`recent-event-${index}`, "text", { role: "mono", text: `${event.type ?? "event"} ${event.identityId ?? ""} ${shortIso(event.observedAt)}\n${compactText(event.reason ?? event.statusPath ?? "", 120)}`, }), ), ]), ]), eveNode("voidbot-context", "grid", { columns: "minmax(0, 1fr)", layout: { gap: 8, overflowX: "hidden" }, }, [ eveNode("selected-channels", "pane", { title: "Channels", density: "compact" }, (selected?.channelPermissions ?? []).slice(0, 8).map((channel, index) => eveNode(`selected-channel-${index}`, "text", { role: "mono", text: `${channel.label ?? "channel"} x${formatNumber(channel.speedMultiplier ?? 1, 2)} ${channel.speechThreshold ?? "threshold"}\n${channel.topic ?? "no topic"}`, }), )), ]), ]), assets: participants .filter((participant) => participant.avatarUrl) .slice(0, 32) .map((participant) => ({ id: `avatar-${participant.identityId}`, kind: "image", uri: participant.avatarUrl, })), }, }; } function compareOperatorPressure(left, right) { return (faceOperatorScore(right) - faceOperatorScore(left)) || String(left.displayName ?? left.identityId ?? "").localeCompare(String(right.displayName ?? right.identityId ?? "")); } function faceOperatorScore(face) { const readyScore = typeof face?.nextTurnInMinutes === "number" && face.nextTurnInMinutes <= 0 ? 25 : 0; const activeScore = face?.activeJobId ? 35 : 0; return activeScore + readyScore + faceMemoryCount(face) * 2 + facePressureCount(face) * 9 + (face?.pendingMentionCount ?? 0) * 18 + (face?.queuedCount ?? 0) * 4 + (face?.heat ?? 0) * 8; } function faceMemoryCount(face) { const counts = face?.faceState?.counts ?? {}; return (counts.shortTerm ?? 0) + (counts.memories ?? 0) + (counts.incubation ?? 0); } function facePressureCount(face) { return face?.faceState?.counts?.pressures ?? 0; } function routeSummary(snapshot, swarmSurfaceOrgan) { const server = swarmSurfaceOrgan?.cultMeshServer ?? {}; const serverStatus = server.status ?? swarmSurfaceOrgan?.lastStatus ?? "missing"; const odinStatus = server.odinCultMeshUri || server.odinRudpEndpoint ? "ok" : "missing"; const lines = [ `store ${snapshot.cultMesh?.writeStatus ?? "pending"} ${shortIso(snapshot.cultMesh?.writtenAt ?? snapshot.generatedAt)}`, `provider ${serverStatus}${server.pid ? ` pid ${server.pid}` : ""}`, `bind ${server.bind ?? "unknown"}`, `odin ${server.odinCultMeshUri ?? "missing"}`, `rudp ${server.odinRudpEndpoint ?? "missing"}`, `cc ${compactPath(server.storePath ?? snapshot.cultMesh?.storePath ?? "unknown", 46)}`, ]; if (server.error) lines.push(`error ${compactText(server.error, 130)}`); return { serverStatus, odinStatus, text: lines.join("\n"), }; } function buildOperatorAlerts(snapshot, context) { const alerts = []; if (snapshot.cultMesh?.writeStatus !== "ok") { alerts.push(`Store write is ${snapshot.cultMesh?.writeStatus ?? "unknown"}; dashboard may be stale.`); } if (!context.swarmSurfaceOrgan) { alerts.push("voidbot-swarm-surface organ is missing from orchestrator state."); } else if (!["ok", "ready", "running"].includes(String(context.swarmSurfaceOrgan.lastStatus ?? "").toLowerCase())) { alerts.push(`Eve surface organ reports ${context.swarmSurfaceOrgan.lastStatus ?? "unknown"}.`); } if (!context.swarmSurfaceOrgan?.cultMeshServer) { alerts.push("CultMesh RUDP provider status is not projected yet."); } else if (!["already_running", "started", "running", "ok"].includes(String(context.swarmSurfaceOrgan.cultMeshServer.status ?? "").toLowerCase())) { alerts.push(`CultMesh RUDP provider is ${context.swarmSurfaceOrgan.cultMeshServer.status ?? "unknown"}.`); } if (!context.watchdog || !["ok", "ready", "running", "skipped_disabled"].includes(String(context.watchdog.lastStatus ?? "").toLowerCase())) { alerts.push(`Watchdog is ${context.watchdog?.lastStatus ?? "missing"}.`); } if ((context.pendingMentions?.length ?? 0) > 0) alerts.push(`${context.pendingMentions.length} pending mention(s) need routing.`); else if ((context.recentMentionActivity?.length ?? 0) > 0) { const latest = context.recentMentionActivity[0]; alerts.push(`Pending mentions are empty; latest mention activity was ${latest.kind ?? "seen"} for ${latest.identityId ?? "unknown"} at ${shortIso(latest.observedAt)}.`); } if ((context.activeTurns?.length ?? 0) > 0) alerts.push(`${context.activeTurns.length} active turn(s) are running.`); if (!alerts.length) alerts.push("No immediate operator alerts."); return alerts; } function mentionMetric(summary, recentMentionActivity) { const pending = summary.pendingMentionCount ?? 0; if (pending > 0) return `${pending} pending`; const latest = recentMentionActivity?.[0] ?? summary.lastMentionActivity; if (!latest) return "0 pending"; const count = latest.mentionCount ?? 1; if (latest.kind === "consumed" || latest.kind === "handled_job") { return `0 pending / ${count} handled`; } return `0 pending / ${latest.kind ?? "seen"}`; } function mentionEmptyText(summary, recentMentionActivity) { const latest = recentMentionActivity?.[0] ?? summary.lastMentionActivity; if (!latest) { return "No pending mentions."; } return `No pending mentions. Recent activity: ${mentionActivitySummary(latest)}.`; } function mentionActivityText(activity) { return `${mentionActivitySummary(activity)}\n${compactText(activity.prompt || activity.mentions?.[0]?.prompt || activity.activeJobId || activity.requestMessageId || "", 150)}`; } function mentionActivitySummary(activity) { const label = activity.kind === "consumed" ? "consumed" : activity.kind === "handled_job" ? "handled job" : activity.kind === "duplicate_intake" ? "duplicate intake" : activity.kind ?? "activity"; const count = activity.mentionCount && activity.mentionCount > 1 ? ` x${activity.mentionCount}` : ""; return `${label}${count} ${activity.identityId ?? "face"} / ${shortIso(activity.observedAt)}`; } function compactPath(value, maxLength = 74) { const text = String(value ?? ""); if (text.length <= maxLength) return text; const tail = text.slice(Math.max(0, text.length - maxLength + 3)); return `...${tail}`; } function compactText(value, maxLength = 240) { const text = String(value ?? "").replace(/\s+/g, " ").trim(); if (text.length <= maxLength) return text; return `${text.slice(0, Math.max(0, maxLength - 1)).trimEnd()}...`; } function eveMetric(id, label, value) { return eveNode(`metric-${stableId(id)}`, "metric", { label, value: String(value ?? "unknown"), }); } function eveBar(id, label, value, percent) { return eveNode(`bar-${stableId(id)}`, "bar", { label, value: String(value ?? "unknown"), percent: clampPercent(percent), }); } function selectDashboardParticipant(snapshot, participants, upcoming) { const preferredId = snapshot?.summary?.nextIdentityId ?? upcoming[0]?.identityId ?? participants[0]?.identityId; return participants.find((participant) => participant.identityId === preferredId) ?? participants[0] ?? null; } function findDashboardLeaf(participant) { const leaves = flattenDashboardLeaves(participant?.faceState?.tree ?? []); if (!leaves.length) return null; return leaves.find((leaf) => leaf.label !== "empty" && ( String(leaf.path ?? "").startsWith("thoughtMemory.shortTerm") || String(leaf.path ?? "").startsWith("thoughtMemory.memories") || String(leaf.path ?? "").startsWith("thoughtMemory.incubation") || String(leaf.path ?? "").startsWith("agencyPressure.pressures") )) ?? leaves[0]; } function flattenDashboardLeaves(nodes) { const output = []; const visit = (node) => { if (!node) return; if (node.kind === "leaf") output.push(node); for (const child of node.children ?? []) visit(child); }; for (const node of nodes ?? []) visit(node); return output; } function turnPercent(value) { if (typeof value !== "number") return 0; return value <= 0 ? 100 : clampPercent(100 - value * 5); } function statusFill(value) { const state = String(value || "missing").toLowerCase(); if (state === "ok" || state === "ready" || state === "skipped_disabled") return 100; if (state === "running") return 82; if (state === "warning" || state === "paused") return 46; return 12; } function clampPercent(value) { const numeric = Number(value); return Number.isFinite(numeric) ? Math.max(0, Math.min(100, numeric)) : 0; } function eveNode(id, kind, props = {}, children = []) { const { layout, style, stateBindings, ...nodeProps } = props ?? {}; return { id, kind, props: nodeProps, ...(layout && typeof layout === "object" ? { layout } : {}), ...(style && typeof style === "object" ? { style } : {}), ...(Array.isArray(stateBindings) && stateBindings.length > 0 ? { stateBindings } : {}), children, }; } function stableId(value) { return String(value ?? "id") .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .replace(/^-+|-+$/g, "") || "id"; } function turnState(turn) { if (turn?.activeJobId) return "active"; if ((turn?.pendingMentionCount ?? 0) > 0) return "mention"; if (turn?.restState?.isNapping) return "nap"; return minutesText(turn?.nextTurnInMinutes); } function minutesText(value) { return typeof value === "number" ? value <= 0 ? "ready" : `${value.toFixed(value < 10 ? 1 : 0)}m` : "unknown"; } function formatNumber(value, decimals) { return typeof value === "number" && Number.isFinite(value) ? value.toFixed(decimals).replace(/\.?0+$/, "") : "?"; } function shortIso(value) { const timestamp = Date.parse(value ?? ""); if (!Number.isFinite(timestamp)) return "unknown"; const date = new Date(timestamp); return `${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; } function timestampMs(value) { const parsed = Date.parse(value ?? ""); return Number.isFinite(parsed) ? parsed : 0; } function findSnapshotOrgan(organs, needle) { const lower = String(needle).toLowerCase(); return organs.find((organ) => String(organ?.id ?? "").toLowerCase().includes(lower) || String(organ?.label ?? "").toLowerCase().includes(lower)); } function renderHtml(snapshot) { return `