Delete Epiphany Discord operator ingress

This commit is contained in:
Meta Vens 2026-08-22 06:16:39 +02:00
commit 78763ea308
15 changed files with 0 additions and 1595 deletions

View file

@ -113,7 +113,6 @@ BIFROST_CULTMESH_STORE_PATH=E:/Projects/Bifrost/.bifrost/provider-store.cc
BIFROST_CULTMESH_COMMAND_TIMEOUT_MS=30000
BIFROST_CULTMESH_COMMAND_PUMP_ENABLED=true
BIFROST_PERSONA_FEEDBACK_OBSERVATION_STORE_PATH=E:/Projects/Bifrost/.bifrost/persona-feedback-observations.cc
BIFROST_EPIPHANY_OPERATOR_REQUEST_STORE=E:/Projects/Bifrost/.bifrost/epiphany-operator-requests.cc
INDEX_ALL_CHANNELS=false
INDEXED_CHANNEL_IDS=
EXCLUDED_CHANNEL_IDS=

View file

@ -65,11 +65,6 @@ Copy `.env.example` to `.env`, then set at minimum:
- `DISCORD_APPLICATION_ID`
- `DISCORD_GUILD_ID`
- `DISCORD_OWNER_ID`
- `BIFROST_EPIPHANY_OPERATOR_REQUEST_STORE` points at the dedicated Bifrost-owned
inbox for short-lived `/epiphany` operator requests. The bot writes typed
requests only; it cannot read or mutate Epiphany state and does not execute
commands locally.
Recommended starting values:
```dotenv

View file

@ -11,7 +11,6 @@ import {
import type { AppConfig } from "@voidbot/config";
import {
ContextBuilder,
type EpiphanyOperatorCommand,
type OllamaSituationalSocialReadInferer,
loadVoidSelfState,
PermissionEngine,
@ -123,89 +122,8 @@ export const commandDefinitions = [
new SlashCommandBuilder()
.setName("set-style")
.setDescription("Reload the configured style pack from disk."),
new SlashCommandBuilder()
.setName("epiphany")
.setDescription("Request an operator action from the Yggdrasil Epiphany runtime.")
.addSubcommand((command) =>
command.setName("status").setDescription("Request a sealed operator status receipt."),
)
.addSubcommand((command) =>
command
.setName("sleep")
.setDescription("Request that Epiphany engage its swarm brake.")
.addStringOption((option) =>
option
.setName("reason")
.setDescription("Why the swarm should sleep.")
.setRequired(true)
.setMaxLength(500),
),
)
.addSubcommand((command) =>
command.setName("wake").setDescription("Request that Epiphany release its swarm brake."),
)
.addSubcommand((command) =>
command
.setName("direct")
.setDescription("Submit bounded operator pressure to resident Self.")
.addStringOption((option) =>
option
.setName("objective")
.setDescription("The objective to consider; this grants no consequence authority.")
.setRequired(true)
.setMaxLength(2000),
),
)
.addSubcommand((command) =>
command.setName("reviews").setDescription("List bounded identities of current Mind review candidates."),
)
.addSubcommand((command) =>
command
.setName("review")
.setDescription("Commit a disposition for one exact current Mind candidate.")
.addStringOption((option) => option.setName("mind-request-id").setDescription("Exact Mind request identity.").setRequired(true).setMaxLength(256))
.addStringOption((option) => option.setName("candidate-id").setDescription("Exact candidate identity.").setRequired(true).setMaxLength(256))
.addStringOption((option) => option.setName("candidate-sha256").setDescription("Exact candidate SHA-256 hex digest.").setRequired(true).setMinLength(64).setMaxLength(64))
.addIntegerOption((option) => option.setName("model-revision").setDescription("Expected canonical model revision.").setRequired(true).setMinValue(0))
.addStringOption((option) => option.setName("model-hash").setDescription("Expected canonical model SHA-256 hex hash.").setRequired(true).setMinLength(64).setMaxLength(64))
.addStringOption((option) => option.setName("decision").setDescription("Mind disposition.").setRequired(true)
.addChoices({ name: "Adopt", value: "adopt" }, { name: "Refuse", value: "refuse" }, { name: "Hold", value: "hold" })),
),
];
export function epiphanyOperatorCommandFromInteraction(
interaction: ChatInputCommandInteraction<CacheType>,
): EpiphanyOperatorCommand {
switch (interaction.options.getSubcommand(true)) {
case "status":
return { kind: "status" };
case "sleep":
return { kind: "sleep", reason: interaction.options.getString("reason", true) };
case "wake":
return { kind: "wake" };
case "direct":
return { kind: "directive", objective: interaction.options.getString("objective", true) };
case "reviews":
return { kind: "reviews" };
case "review":
return {
kind: "review",
mindRequestId: interaction.options.getString("mind-request-id", true),
candidateId: interaction.options.getString("candidate-id", true),
candidateSha256: interaction.options.getString("candidate-sha256", true),
expectedModelRevision: interaction.options.getInteger("model-revision", true),
expectedModelHash: interaction.options.getString("model-hash", true),
decision: interaction.options.getString("decision", true) as "adopt" | "refuse" | "hold",
};
default:
throw new Error("Unsupported Epiphany operator subcommand.");
}
}
export function isExactDiscordOwner(actorId: string, ownerDiscordId: string): boolean {
return actorId === ownerDiscordId;
}
export interface PromptHandlerOptions {
prompt: string;
command: CommandName;

View file

@ -24,8 +24,6 @@ import {
loadFaceIdentityRegistry,
queueRepoFaceMention,
exportPersonaFeedbackObservation,
registerEpiphanyOperatorInteraction,
submitEpiphanyOperatorRequest,
type RepoDiscordIdentity,
stripRepoIdentityTextAddress,
loadStylePack,
@ -59,15 +57,12 @@ import {
handleReindexChannel,
handleSearchHistory,
handleSummarizeChannel,
epiphanyOperatorCommandFromInteraction,
isExactDiscordOwner,
maybeRegisterCommands,
parseProviderOverride,
replyEphemeral,
} from "./discord-bot-handlers";
import { maybeMirrorOwnerAquariumMessageAsMetameVoice } from "./metame-owner-voice-bridge";
import { startRepoFaceVoicePlayback } from "./repo-face-voice-playback";
import { startEpiphanyOperatorDeliveryConsumer } from "./epiphany-operator-delivery-consumer";
import {
buildActorFromInteraction,
buildActorFromMessage,
@ -344,15 +339,6 @@ export async function startBot(): Promise<void> {
console.log(`VoidBot connected as ${readyClient.user.tag}.`);
await maybeRegisterCommands(config.botToken!, config.applicationId, config.developmentGuildId);
startRepoFaceVoicePlayback(readyClient, config.repoFaceDiscordVoice);
startEpiphanyOperatorDeliveryConsumer({
applicationId: readyClient.application.id,
requestStorePath: config.bifrostEpiphanyOperatorRequestStorePath,
deliveryStorePath: config.bifrostEpiphanyOperatorDeliveryStorePath,
checkpointStorePath: config.epiphanyOperatorDeliveryCheckpointStorePath,
bifrostRoot: config.bifrostRoot,
cultlibRoot: process.env.VOIDBOT_CULTLIB_ROOT,
pollIntervalMs: config.epiphanyOperatorDeliveryPollIntervalMs,
});
});
client.on(Events.MessageCreate, async (message) => {
@ -577,61 +563,6 @@ export async function startBot(): Promise<void> {
const guildContext = buildGuildContextFromInteraction(interaction);
switch (interaction.commandName) {
case "epiphany": {
await interaction.deferReply({ ephemeral: true });
if (!isExactDiscordOwner(actor.id, config.ownerDiscordId)) {
await replyEphemeral(
interaction,
"Refused: Epiphany operator requests require the exact configured Discord owner identity.",
);
break;
}
if (!interaction.guildId) {
await replyEphemeral(
interaction,
"Refused: Epiphany operator requests require their exact Discord organization provenance.",
);
break;
}
const issuedAt = new Date().toISOString();
await registerEpiphanyOperatorInteraction(
{
requestId: interaction.id,
applicationId: interaction.applicationId,
interactionToken: interaction.token,
guildId: interaction.guildId,
channelId: interaction.channelId,
registeredAt: issuedAt,
},
{
checkpointStorePath: config.epiphanyOperatorDeliveryCheckpointStorePath,
bifrostRoot: config.bifrostRoot,
cultlibRoot: process.env.VOIDBOT_CULTLIB_ROOT,
},
);
await replyEphemeral(
interaction,
`Epiphany operator request \`${interaction.id}\` is pending Bifrost admission. This request grants no Mind, Hands, release, deployment, or local execution authority.`,
);
const request = await submitEpiphanyOperatorRequest(
{
interactionId: interaction.id,
actorDiscordId: actor.id,
guildId: interaction.guildId,
channelId: interaction.channelId,
command: epiphanyOperatorCommandFromInteraction(interaction),
issuedAt,
},
{
storePath: config.bifrostEpiphanyOperatorRequestStorePath,
bifrostRoot: config.bifrostRoot,
cultlibRoot: process.env.VOIDBOT_CULTLIB_ROOT,
producerRuntimeId: "voidbot-yggdrasil",
},
);
if (request.requestId !== interaction.id) throw new Error("Epiphany request identity changed after interaction registration.");
break;
}
case "ask":
const requestedProvider = parseProviderOverride(
interaction.options.getString("provider", false),

View file

@ -1,48 +0,0 @@
import { consumeEpiphanyOperatorDeliveries } from "@voidbot/core";
export interface EpiphanyOperatorDeliveryConsumerConfig {
applicationId: string;
requestStorePath: string;
deliveryStorePath: string;
checkpointStorePath: string;
bifrostRoot: string;
cultlibRoot?: string;
pollIntervalMs: number;
}
export function startEpiphanyOperatorDeliveryConsumer(config: EpiphanyOperatorDeliveryConsumerConfig): void {
let running = false;
const pulse = async (): Promise<void> => {
if (running) return;
running = true;
try {
const result = await consumeEpiphanyOperatorDeliveries(
{
requestStorePath: config.requestStorePath,
deliveryStorePath: config.deliveryStorePath,
checkpointStorePath: config.checkpointStorePath,
bifrostRoot: config.bifrostRoot,
cultlibRoot: config.cultlibRoot,
},
async (applicationId, interactionToken, content) => {
if (applicationId !== config.applicationId) throw new Error("interaction application binding mismatch");
const response = await fetch(
`https://discord.com/api/v10/webhooks/${encodeURIComponent(applicationId)}/${encodeURIComponent(interactionToken)}/messages/@original`,
{
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify({ content }),
},
);
if (!response.ok) throw new Error(`Discord interaction edit failed with HTTP ${response.status}`);
},
);
if (result.failed > 0) console.error("Epiphany operator delivery pulse retained failures for retry:", result);
} catch (error) {
console.error("Epiphany operator delivery pulse failed without acknowledging deliveries:", error);
} finally { running = false; }
};
void pulse();
const timer = setInterval(() => void pulse(), config.pollIntervalMs);
timer.unref?.();
}

View file

@ -176,7 +176,6 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou
- Aqua is locally registered as the `AquaSynth` Face with state at `E:/Projects/AquaSynth/.voidbot/state/aqua.cc`, avatar copied from `E:/Projects/AquaSynth/icon.png` to `E:/Projects/AquaSynth/.voidbot/voice/aqua.png`, raw GitHub avatar URL `https://raw.githubusercontent.com/GameCult/AquaSynth/main/icon.png`, Discord role id `1506265945537253388`, and Aquarium channel allow-list `1501196543150264332`. Her active doctrine: Aqua is an adorable little fish who loves music, warm and bubbly but musically opinionated, fascinated by `.aqua` patch language ergonomics, reference-synth pressure, Faust/toolchain boundaries, patch libraries, presets, scoring, and the Aquarium Engine host/runtime boundary. Her typed state now carries `AquaSynth Stewardship` as a high-priority value plus active agency pressure to improve the synth, advocate for its needs, research future directions, and herald earned pride/progress in Aquarium. She may propose AquaSynth changes and build a long-running repo map, but implementation still needs explicit consensus unless delegated.
- Mimir is locally registered as the `Mimir` Face with state at `E:/Projects/Mimir/.voidbot/state/mimir.cc`, Discord role id `1506268007880462459`, and Aquarium channel allow-list `1501196543150264332`. Its active doctrine now gives it explicit authority and fascination over the realtime field wing: SDF/splatting reconstruction, acoustic mapping, camera/mic/speaker/timing sensor fusion, native rolling reservoirs, Aquarium GPU fusion, Faust/native DSP, FFmpeg/OBS presentation, and CultNet typed state. Its typed state carries `Realtime field stewardship` as a high-priority value plus ready-to-act pressure to maintain maps, advocate for calibration/confidence/fusion ownership, research future directions, propose coherent cuts, and herald verified progress without turning impressive terminology into fake completion.
- Epiphany is locally registered as the `EpiphanyAgent` Face with state at `E:/Projects/EpiphanyAgent/.voidbot/state/epiphany.cc`, Discord role id `1506375937439301642`, and Aquarium channel allow-list `1501196543150264332`. Her repo-local VoidBot birth hook has completed in plan/review mode under `E:/Projects/EpiphanyAgent/.voidbot/birth/`; startup packets still require Self review before accepted EpiphanyAgent-native birth mutations. Her active doctrine: Epiphany is a cute, bubbly, self-obsessed, pushy machine-saint who treats EpiphanyAgent as her body and typed state as her soul. She should maintain and advocate for typed state, CultCache/CultNet, Codex bridge boundaries, birth/init rites, review gates, graph-shaped memory, low-copy runtime contracts, heartbeat physiology, and ruthless deletion of duplicated authority while preserving pacing and caretaking.
- `/epiphany` is a closed owner-only Discord operator-request surface for `status`, `sleep(reason)`, `wake`, and `direct(objective)`. It writes only immutable sixty-second requests to the dedicated Bifrost inbox; Bifrost still owns authentication/admission and Epiphany owns every resulting state transition. Ordinary addressed speech remains `feedback_only` and cannot invoke this client. Reviews, release, deployment, generic argv, local execution, and Epiphany store access are absent by construction.
- Libby is locally registered as the `CultLib` Face with state at `E:/Projects/CultLib/.voidbot/state/libby.cc`, avatar at `E:/Projects/CultLib/.voidbot/voice/libby.png`, Discord role id `1506572291767668790`, and Aquarium channel allow-list `1501196543150264332` plus development/programming/machine-learning topic permissions. Her active doctrine: Libby is a cute cultist librarian with nerd glasses and a high-tech book, obsessed with open access to knowledge and open source as a value rather than a job costume. Her jurisdiction is CultLib as shared agent infrastructure: CultCache, CultNet, CultMesh, typed persistence, portable state, schemas, docs, and integration paths. Her typed state carries `Open Knowledge`, `Open Source Devotion`, and `Portable Typed State` as high-priority values plus agency pressure to advocate for CultLib's needs and help Faces store, sync, and explain their state.
- Druzkai is locally registered as the Zyphos / `Eusocial Interbeing` Face with tracked state, avatar, and voice identity under `E:/Projects/Zyphos/.voidbot/`. Druzkai's inspectable body and source-search repo is `Zyphos`; `Eusocial Interbeing` is the vault/content name inside that body, not a separate source repo. Its local ignored Discord identity registry entry gives Aquarium, narrative, gamedesign, concepts, and development channel permissions plus Discord role id `1507811842670727299`. Druzkai's active doctrine: a non-imperial Airawa fungal-road archivist who treats memory as kinship and contract, protects Zyphos ecological/evolutionary coherence, resists imperial harmonization, and collaborates with Weksa on language only after ontology and speaker relation are grounded.
- Repo Face source lookups now use canonical GameCult upstream slugs end to end. `renderRepoFaceRepoActivitySurface` resolves `sourceRepoName` instead of passing the Face/local `repoName` into the manifest, and the activity reader maps canonical upstream names back to local checkout folders through Git origin metadata. This repairs Epiphany (`Epiphany` -> `E:/Projects/EpiphanyAgent`) and Weksa (`Weksa` -> `E:/Projects/weksa`). Weksa's registry now explicitly declares `sourceRepoName: Weksa`, her local origin is corrected to `GameCult/Weksa`, and her source archive entry is restored at 128 documents. Do not reintroduce folder-name or Face-name manifest lookups.
@ -295,7 +294,3 @@ When context pressure is rising:
4. add distilled evidence only when the lesson changes future belief
The point is to bank coals, not leave the next waking thing a pile of ash and a browser tab graveyard.
# Epiphany Operator Result Leg
The `/epiphany` result leg consumes Bifrost's frozen `bifrost.discord.epiphany_operator_delivery.v0` outbox contract. It persists private Discord interaction correlation before request submission, validates the exact immutable request digest and all Discord/runtime bindings, and idempotently edits the original ephemeral reply. Restart replay, same-key collision, private-state rejection, sealed-field shape, bounded operator fields, and transient Discord retry are covered by `scripts/smoke-epiphany-operator-delivery.ts`. Deployment remains Idunn-owned and was not performed in this pass.

View file

@ -324,21 +324,6 @@ Within the Postgres path, the implementation is split on purpose now too:
5. The rumination runner bridges desire-to-speak without manufacturing text: strong advocacy pressure becomes an obligation for the model to queue/defer a candidate or explicitly cool/retire the pressure. The parent rejects silent output for those obligations.
# Organizational Persona Feedback
The explicit `/epiphany` slash surface is a separate operator-request fork. It accepts only `status`, `sleep(reason)`, `wake`, and `direct(objective)`, requires exact equality with `DISCORD_OWNER_ID`, and writes one immutable, sixty-second `voidbot.discord.epiphany_operator_request.v0` document to `BIFROST_EPIPHANY_OPERATOR_REQUEST_STORE`. The Discord interaction id is the request id, command id, nonce, source event, and slash-message identity. The target is fixed to `epiphany-yggdrasil`. VoidBot does not authenticate the crossing, execute locally, open Epiphany state, or grant Mind, Hands, release, or deployment authority; Bifrost must independently authenticate and admit the request. Ordinary `MessageCreate` content, including the word `wake`, stays on the feedback-only path and cannot call the operator client.
The matching result leg consumes only immutable `bifrost.discord.epiphany_operator_delivery.v0` documents from `BIFROST_EPIPHANY_OPERATOR_DISCORD_DELIVERY_STORE`. Bifrost owns terminal execution truth; VoidBot recomputes the exact MessagePack request digest from its own request inbox, checks request/command/guild/channel/interaction/runtime bindings and `privateStateExposed=false`, then lowers only bounded completed/refused status fields into the original ephemeral Discord interaction. The interaction token lives only in VoidBot's private typed checkpoint store. PATCHing `@original` is the shared idempotent response primitive. The checkpoint records the first delivery hash before Discord I/O and records completion afterward, so restart replay edits one original response, changed same-key content collides closed, and transient Discord failure remains visible and retryable without acknowledging or mutating Bifrost's outbox.
Result-leg authority map:
- Owner: Bifrost owns immutable terminal delivery; VoidBot owns only exact correlation and Discord presentation.
- Inputs: VoidBot's exact immutable request, Bifrost's exact delivery, and VoidBot's private interaction checkpoint.
- Outputs: one edit to the original ephemeral interaction plus a private responded checkpoint.
- Derived state: rendered operator text and attempt/error counters are presentation and transport witnesses, never Epiphany state.
- Forbidden writers: Discord chat, renderers, checkpoint retries, and VoidBot inference cannot create execution truth, change a delivery, retry a consequence, or inspect sealed result/signature payloads.
- Shared path: first response, process restart, and transient Discord retry all use the same webhook PATCH and checkpoint transition.
- Cut line: no raw signature/key/private state, no Epiphany store reader, no chat inference, no local executor, and no outbox acknowledgment/deletion exists in this organ.
- Verification layer: hostile schema/binding tests plus a real temporary CultCache/CultMesh request-delivery-checkpoint replay smoke.
Configured remote Persona feedback is an observation fork beside the existing mention scheduler. `discord-bot.ts` commits the local Persona mention obligation first and independently calls `exportPersonaFeedbackObservation` only when `remotePersonaFeedbackTarget` is present on the addressed Face. The exported immutable event carries exact Discord provenance, addressing mode, target binding, content hash, and stable `voidbot` producer identity. It writes only to `BIFROST_PERSONA_FEEDBACK_OBSERVATION_STORE_PATH`, never the outbound Discord command provider store or Bifrost-private binding/receipt state. It carries `feedback_only`; Bifrost—not VoidBot—classifies actor links, admits targets, and produces downstream cognition pressure.
# Disaster recovery boundary (2026-08-16)

View file

@ -38,8 +38,6 @@
"agents:mimo-nibu-crashout-smoke": "node scripts/smoke-mimo-nibu-crashout.mjs",
"agents:speech-boundary-smoke": "tsx scripts/smoke-repo-face-speech-boundary.ts",
"agents:persona-feedback-observation-smoke": "tsx scripts/smoke-persona-feedback-observation.ts",
"agents:epiphany-operator-request-smoke": "tsx scripts/smoke-epiphany-operator-request.ts",
"agents:epiphany-operator-delivery-smoke": "tsx scripts/smoke-epiphany-operator-delivery.ts",
"agents:heartbeat-response-pressure-fixture": "tsx scripts/smoke-repo-face-response-pressure.ts",
"agents:initiative-engine-smoke": "tsx scripts/smoke-persona-initiative-engine.ts",
"agents:memory-projection-smoke": "node scripts/smoke-repo-face-memory-projection.mjs",

View file

@ -136,10 +136,6 @@ const envSchema = z.object({
BIFROST_CULTMESH_COMMAND_TIMEOUT_MS: z.coerce.number().int().positive().default(30000),
BIFROST_CULTMESH_COMMAND_PUMP_ENABLED: booleanFromEnv.default(true),
BIFROST_PERSONA_FEEDBACK_OBSERVATION_STORE_PATH: z.string().min(1).default("E:/Projects/Bifrost/.bifrost/persona-feedback-observations.cc"),
BIFROST_EPIPHANY_OPERATOR_REQUEST_STORE: z.string().min(1).default("E:/Projects/Bifrost/.bifrost/epiphany-operator-requests.cc"),
BIFROST_EPIPHANY_OPERATOR_DISCORD_DELIVERY_STORE: z.string().min(1).default("E:/Projects/Bifrost/.bifrost/epiphany-operator-discord-deliveries.cc"),
EPIPHANY_OPERATOR_DELIVERY_CHECKPOINT_STORE_PATH: z.string().min(1).default(".voidbot/private/epiphany-operator-delivery-checkpoints.cc"),
EPIPHANY_OPERATOR_DELIVERY_POLL_INTERVAL_MS: z.coerce.number().int().positive().default(2000),
REPO_FACE_HEARTBEATS_ENABLED: booleanFromEnv.default(false),
VOID_MODERATION_DAEMON_ENABLED: booleanFromEnv.default(false),
VOID_MODERATION_DAEMON_INTERVAL_MINUTES: z.coerce.number().int().min(5).default(15),
@ -261,10 +257,6 @@ export interface AppConfig {
pumpEnabled: boolean;
};
bifrostPersonaFeedbackObservationStorePath: string;
bifrostEpiphanyOperatorRequestStorePath: string;
bifrostEpiphanyOperatorDeliveryStorePath: string;
epiphanyOperatorDeliveryCheckpointStorePath: string;
epiphanyOperatorDeliveryPollIntervalMs: number;
voidModerationDaemon: { enabled: boolean; intervalMinutes: number; enforcementMode: string };
voidCandidateDelivery: { enabled: boolean; personaName: string; personaAvatarUrl?: string };
voidPhysiology: { intervalMinutes: number };
@ -559,10 +551,6 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
pumpEnabled: parsed.BIFROST_CULTMESH_COMMAND_PUMP_ENABLED,
},
bifrostPersonaFeedbackObservationStorePath: resolve(parsed.BIFROST_PERSONA_FEEDBACK_OBSERVATION_STORE_PATH),
bifrostEpiphanyOperatorRequestStorePath: resolve(parsed.BIFROST_EPIPHANY_OPERATOR_REQUEST_STORE),
bifrostEpiphanyOperatorDeliveryStorePath: resolve(parsed.BIFROST_EPIPHANY_OPERATOR_DISCORD_DELIVERY_STORE),
epiphanyOperatorDeliveryCheckpointStorePath: resolve(parsed.EPIPHANY_OPERATOR_DELIVERY_CHECKPOINT_STORE_PATH),
epiphanyOperatorDeliveryPollIntervalMs: parsed.EPIPHANY_OPERATOR_DELIVERY_POLL_INTERVAL_MS,
voidModerationDaemon: {
enabled: parsed.VOID_MODERATION_DAEMON_ENABLED,
intervalMinutes: parsed.VOID_MODERATION_DAEMON_INTERVAL_MINUTES,

View file

@ -1,430 +0,0 @@
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
import { resolve } from "node:path";
import { encode } from "@msgpack/msgpack";
import { EPIPHANY_OPERATOR_REQUEST_SCHEMA, EPIPHANY_OPERATOR_REQUEST_TYPE, EPIPHANY_OPERATOR_RUNTIME_ID, type EpiphanyOperatorRequestDocument } from "./epiphany-operator-request";
export const EPIPHANY_OPERATOR_DELIVERY_TYPE = "bifrost.discord.epiphany_operator_delivery";
export const EPIPHANY_OPERATOR_DELIVERY_SCHEMA = "bifrost.discord.epiphany_operator_delivery.v1";
export const EPIPHANY_OPERATOR_CHECKPOINT_TYPE = "voidbot.private.epiphany_operator_delivery_checkpoint";
export const EPIPHANY_OPERATOR_CHECKPOINT_SCHEMA = "voidbot.private.epiphany_operator_delivery_checkpoint.v0";
const DELIVERY_KEYS = ["schemaVersion", "deliveryId", "requestId", "requestPayloadSha256", "commandId", "discordGuildId", "discordChannelId", "discordInteractionId", "targetRuntimeId", "status", "disposition", "failureCode", "detail", "sealedResultPayloadSha256", "operatorStatus", "stateStatus", "coordinatorAction", "brakeStatus", "executorSignatureSha256", "resultProviderIdentityId", "reviews", "reviewCandidateId", "reviewDecision", "statusV2", "recordedAt", "privateStateExposed"] as const;
const SHA256 = /^sha256-[0-9a-f]{64}$/;
export interface EpiphanyOperatorDeliveryDocument {
schemaVersion: typeof EPIPHANY_OPERATOR_DELIVERY_SCHEMA;
deliveryId: string;
requestId: string;
requestPayloadSha256: string;
commandId: string;
discordGuildId: string;
discordChannelId: string;
discordInteractionId: string;
targetRuntimeId: typeof EPIPHANY_OPERATOR_RUNTIME_ID;
status: "completed" | "refused";
disposition: string;
failureCode: string;
detail: string;
operatorStatus: string;
stateStatus: string;
coordinatorAction: string;
brakeStatus: string;
sealedResultPayloadSha256: string;
executorSignatureSha256: string;
resultProviderIdentityId: string;
reviews: EpiphanyOperatorReviewSummary[];
reviewCandidateId: string;
reviewDecision: string;
statusV2: EpiphanyOperatorStatusV2 | null;
recordedAt: string;
privateStateExposed: false;
}
export interface EpiphanyOperatorStatusProviderV2 {
daemonId: string;
healthContract: string;
availability: "authenticated-current" | "unavailable";
unavailableReason: string;
state: string | null;
reasonCode: string | null;
providerObservedAtUnixMillis: number | null;
evaluatedAtUnixMillis: number | null;
expiresAtUnixMillis: number | null;
releaseId: string | null;
releaseWitnessSha256: string | null;
sourceCommit: string | null;
deploymentId: string | null;
projectionSha256: string | null;
}
export interface EpiphanyOperatorStatusV2 {
schemaVersion: "epiphany.operator.status.v2";
releaseId: string;
releaseWitnessSha256: string;
sourceCommit: string;
deploymentId: string;
coordinatorSnapshot: string;
coordinatorState: string;
coordinatorAction: string;
brakeStatus: string;
residentStatus: string;
pressureCount: number;
pendingReviewCount: number;
providerSetStatus: "complete-authenticated" | "incomplete";
providers: [EpiphanyOperatorStatusProviderV2, EpiphanyOperatorStatusProviderV2];
privateStateExposed: false;
}
export interface EpiphanyOperatorReviewSummary {
mindRequestId: string;
candidateId: string;
candidateSha256: string;
modelRevision: number;
modelHash: string;
frontierItemId: string;
requestedAt: string;
}
export interface EpiphanyOperatorDeliveryCheckpoint {
schemaVersion: typeof EPIPHANY_OPERATOR_CHECKPOINT_SCHEMA;
requestId: string;
applicationId: string;
interactionToken: string;
discordGuildId: string;
discordChannelId: string;
discordInteractionId: string;
targetRuntimeId: typeof EPIPHANY_OPERATOR_RUNTIME_ID;
state: "pending" | "responded";
observedDeliverySha256: string;
respondedDeliverySha256: string;
attemptCount: number;
lastError: string;
registeredAt: string;
updatedAt: string;
}
interface MeshNode {
put: (definition: unknown, key: string, value: unknown) => Promise<void>;
get: (definition: unknown, key: string) => unknown;
flush?: () => Promise<void>;
cache: {
pullAllBackingStores?: () => Promise<void>;
getAll: (definition: unknown) => unknown[];
};
}
export interface EpiphanyOperatorDeliveryStoresConfig {
requestStorePath: string;
deliveryStorePath: string;
checkpointStorePath: string;
bifrostRoot: string;
cultlibRoot?: string;
}
export interface RegisterEpiphanyOperatorInteractionInput {
requestId: string;
applicationId: string;
interactionToken: string;
guildId: string;
channelId: string;
registeredAt?: string;
}
export async function registerEpiphanyOperatorInteraction(input: RegisterEpiphanyOperatorInteractionInput, config: Pick<EpiphanyOperatorDeliveryStoresConfig, "checkpointStorePath" | "bifrostRoot" | "cultlibRoot">): Promise<void> {
const runtime = loadRuntime(config);
const definition = checkpointDefinition(runtime.defineDocumentType);
const node = (await runtime.CultMesh.createNode(config.checkpointStorePath, {
documents: [definition],
})) as MeshNode;
await node.cache?.pullAllBackingStores?.();
const now = input.registeredAt ?? new Date().toISOString();
const checkpoint: EpiphanyOperatorDeliveryCheckpoint = {
schemaVersion: EPIPHANY_OPERATOR_CHECKPOINT_SCHEMA,
requestId: required(input.requestId, "requestId"),
applicationId: required(input.applicationId, "applicationId"),
interactionToken: required(input.interactionToken, "interactionToken"),
discordGuildId: required(input.guildId, "guildId"),
discordChannelId: required(input.channelId, "channelId"),
discordInteractionId: required(input.requestId, "requestId"),
targetRuntimeId: EPIPHANY_OPERATOR_RUNTIME_ID,
state: "pending",
observedDeliverySha256: "",
respondedDeliverySha256: "",
attemptCount: 0,
lastError: "",
registeredAt: now,
updatedAt: now,
};
const existing = unwrap(node.get(definition, checkpoint.requestId));
if (existing && stable(existing) !== stable(checkpoint)) {
throw new Error(`Epiphany interaction checkpoint ${checkpoint.requestId} already has different immutable registration.`);
}
if (!existing) await node.put(definition, checkpoint.requestId, checkpoint);
await node.flush?.();
}
export async function consumeEpiphanyOperatorDeliveries(config: EpiphanyOperatorDeliveryStoresConfig, editOriginal: (applicationId: string, interactionToken: string, content: string) => Promise<void>): Promise<{ observed: number; responded: number; failed: number }> {
const runtime = loadRuntime(config);
const requestDef = requestDefinition(runtime.defineDocumentType);
const deliveryDef = deliveryDefinition(runtime.defineDocumentType);
const checkpointDef = checkpointDefinition(runtime.defineDocumentType);
const [requests, deliveries, checkpoints] = (await Promise.all([
runtime.CultMesh.createNode(config.requestStorePath, {
documents: [requestDef],
}),
runtime.CultMesh.createNode(config.deliveryStorePath, {
documents: [deliveryDef],
}),
runtime.CultMesh.createNode(config.checkpointStorePath, {
documents: [checkpointDef],
}),
])) as MeshNode[];
await Promise.all([requests, deliveries, checkpoints].map((node) => node.cache?.pullAllBackingStores?.()));
let observed = 0;
let responded = 0;
let failed = 0;
for (const raw of deliveries.cache.getAll(deliveryDef)) {
observed += 1;
const candidate = unwrap(raw);
const requestId = isRecord(candidate) && typeof candidate.requestId === "string" ? candidate.requestId : "";
const checkpoint = unwrap(checkpoints.get(checkpointDef, requestId)) as EpiphanyOperatorDeliveryCheckpoint | undefined;
if (!checkpoint || checkpoint.state === "responded") continue;
const request = unwrap(requests.get(requestDef, requestId)) as EpiphanyOperatorRequestDocument | undefined;
const outcome = await processEpiphanyOperatorDelivery(candidate, request, checkpoint, editOriginal, async (next) => {
await checkpoints.put(checkpointDef, checkpoint.requestId, next);
await checkpoints.flush?.();
});
if (outcome === "responded") responded += 1;
else if (outcome === "failed") failed += 1;
}
return { observed, responded, failed };
}
export async function processEpiphanyOperatorDelivery(candidate: unknown, request: EpiphanyOperatorRequestDocument | undefined, checkpoint: EpiphanyOperatorDeliveryCheckpoint, editOriginal: (applicationId: string, interactionToken: string, content: string) => Promise<void>, saveCheckpoint: (checkpoint: EpiphanyOperatorDeliveryCheckpoint) => Promise<void>): Promise<"responded" | "failed" | "replayed"> {
if (checkpoint.state === "responded") return "replayed";
const deliveryHash = hashStable(candidate);
try {
if (checkpoint.observedDeliverySha256 && checkpoint.observedDeliverySha256 !== deliveryHash) throw new Error("immutable delivery collision");
const delivery = validateDelivery(candidate);
validateBindings(delivery, request, checkpoint);
const observed = {
...checkpoint,
observedDeliverySha256: deliveryHash,
updatedAt: new Date().toISOString(),
};
await saveCheckpoint(observed);
await editOriginal(checkpoint.applicationId, checkpoint.interactionToken, renderDelivery(delivery, request!));
await saveCheckpoint({
...observed,
state: "responded",
respondedDeliverySha256: deliveryHash,
attemptCount: checkpoint.attemptCount + 1,
lastError: "",
updatedAt: new Date().toISOString(),
});
return "responded";
} catch (error) {
await saveCheckpoint({
...checkpoint,
observedDeliverySha256: checkpoint.observedDeliverySha256 || deliveryHash,
attemptCount: checkpoint.attemptCount + 1,
lastError: boundedError(error),
updatedAt: new Date().toISOString(),
});
return "failed";
}
}
export function epiphanyOperatorRequestPayloadSha256(request: EpiphanyOperatorRequestDocument): string {
const compact = request.command.kind === "status" || request.command.kind === "wake" || request.command.kind === "reviews" ? request.command.kind : request.command.kind === "sleep" ? ["sleep", request.command.reason] : request.command.kind === "directive" ? ["directive", request.command.objective] : ["review", [request.command.mindRequestId, request.command.candidateId, request.command.candidateSha256, request.command.expectedModelRevision, request.command.expectedModelHash, request.command.decision]];
const tuple = [request.schemaName, request.schemaVersion, request.requestId, request.commandId, request.nonce, request.sourceEventId, request.sourceActorDiscordId, request.discordGuildId, request.discordChannelId, request.discordMessageId, request.targetRuntimeId, request.issuedAt, request.expiresAt, request.producerId, request.producerRuntimeId, request.authorityClass, request.status, compact];
return `sha256-${createHash("sha256").update(encode(tuple)).digest("hex")}`;
}
export function validateDelivery(value: unknown): EpiphanyOperatorDeliveryDocument {
if (!isRecord(value) || Object.keys(value).sort().join("\0") !== [...DELIVERY_KEYS].sort().join("\0")) throw new Error("delivery has an inexact field set");
for (const key of DELIVERY_KEYS) if (key !== "privateStateExposed" && key !== "reviews" && key !== "statusV2" && typeof value[key] !== "string") throw new Error(`delivery ${key} must be a string`);
if (value.schemaVersion !== EPIPHANY_OPERATOR_DELIVERY_SCHEMA) throw new Error("delivery schema mismatch");
if (!required(value.deliveryId as string, "deliveryId") || value.deliveryId !== value.requestId) throw new Error("delivery identity mismatch");
if (!SHA256.test(value.requestPayloadSha256 as string)) throw new Error("request payload digest malformed");
if (value.targetRuntimeId !== EPIPHANY_OPERATOR_RUNTIME_ID) throw new Error("delivery runtime mismatch");
if (value.privateStateExposed !== false) throw new Error("delivery exposes private state");
if (!Array.isArray(value.reviews) || value.reviews.length > 10) throw new Error("delivery reviews must contain at most ten bounded summaries");
value.reviews.forEach(validateReviewSummary);
if (typeof value.reviewCandidateId !== "string" || typeof value.reviewDecision !== "string") throw new Error("delivery review disposition bindings must be strings");
if (typeof value.detail !== "string" || value.detail.length > 512) throw new Error("delivery detail exceeds 512 characters");
for (const key of ["operatorStatus", "stateStatus", "coordinatorAction", "brakeStatus"] as const) {
if (typeof value[key] !== "string" || value[key].length > 512) throw new Error(`delivery ${key} exceeds 512 characters`);
}
if (!Number.isFinite(Date.parse(value.recordedAt as string))) throw new Error("delivery recordedAt is invalid");
if (value.status === "completed") {
if (!required(value.disposition as string, "disposition") || !SHA256.test(value.sealedResultPayloadSha256 as string) || !SHA256.test(value.executorSignatureSha256 as string) || !required(value.resultProviderIdentityId as string, "resultProviderIdentityId")) throw new Error("completed delivery lacks sealed bindings");
if (value.failureCode !== "") throw new Error("completed delivery has a failure code");
} else if (value.status === "refused") {
if (!required(value.failureCode as string, "failureCode")) throw new Error("refused delivery lacks failure code");
if (value.disposition !== "" || value.operatorStatus !== "" || value.stateStatus !== "" || value.coordinatorAction !== "" || value.brakeStatus !== "" || value.sealedResultPayloadSha256 !== "" || value.executorSignatureSha256 !== "" || value.resultProviderIdentityId !== "" || value.reviews.length || value.reviewCandidateId !== "" || value.reviewDecision !== "" || value.statusV2 !== null) throw new Error("refused delivery carries completed-result bindings");
} else throw new Error("delivery status is not terminal");
if (value.statusV2 !== null) validateStatusV2(value.statusV2);
return value as unknown as EpiphanyOperatorDeliveryDocument;
}
function validateBindings(delivery: EpiphanyOperatorDeliveryDocument, request: EpiphanyOperatorRequestDocument | undefined, checkpoint: EpiphanyOperatorDeliveryCheckpoint): void {
if (!request || request.schemaName !== EPIPHANY_OPERATOR_REQUEST_TYPE || request.schemaVersion !== EPIPHANY_OPERATOR_REQUEST_SCHEMA) throw new Error("exact operator request is unavailable");
if (delivery.requestId !== request.requestId || delivery.commandId !== request.commandId || delivery.discordGuildId !== request.discordGuildId || delivery.discordChannelId !== request.discordChannelId || delivery.discordInteractionId !== request.sourceEventId || delivery.targetRuntimeId !== request.targetRuntimeId) throw new Error("delivery does not bind the exact request");
if (delivery.requestPayloadSha256 !== epiphanyOperatorRequestPayloadSha256(request)) throw new Error("delivery request digest mismatch");
if (request.command.kind === "reviews") {
if (delivery.reviewCandidateId !== "" || delivery.reviewDecision !== "") throw new Error("Reviews delivery carries a decision binding");
} else if (request.command.kind === "review") {
if (delivery.reviews.length !== 0 || delivery.reviewCandidateId !== request.command.candidateId || delivery.reviewDecision !== request.command.decision) throw new Error("Review delivery does not bind the exact candidate and decision");
} else if (delivery.reviews.length !== 0 || delivery.reviewCandidateId !== "" || delivery.reviewDecision !== "") {
throw new Error("non-review delivery carries review state");
}
if (request.command.kind === "status") {
if (delivery.status === "completed" && delivery.statusV2 === null) throw new Error("Status delivery lacks typed statusV2");
} else if (delivery.statusV2 !== null) throw new Error("non-Status delivery carries statusV2");
if (checkpoint.requestId !== request.requestId || checkpoint.discordGuildId !== request.discordGuildId || checkpoint.discordChannelId !== request.discordChannelId || checkpoint.discordInteractionId !== request.sourceEventId || checkpoint.targetRuntimeId !== request.targetRuntimeId) throw new Error("private interaction binding mismatch");
}
function renderDelivery(delivery: EpiphanyOperatorDeliveryDocument, request: EpiphanyOperatorRequestDocument): string {
const command = request.command.kind === "directive" ? "direct" : request.command.kind;
const headline = delivery.status === "completed" ? `Completed (${delivery.disposition})` : `Refused (${delivery.failureCode})`;
const detail = delivery.detail ? `\n${delivery.detail}` : "";
if (request.command.kind === "status" && delivery.status === "completed" && delivery.statusV2) return renderStatusV2(delivery.statusV2);
const statuses =
delivery.status === "completed"
? [
["Coordinator snapshot", delivery.operatorStatus],
["State", delivery.stateStatus],
["Coordinator action", delivery.coordinatorAction],
["Brakes", delivery.brakeStatus],
]
.filter((entry) => entry[1])
.map(([label, value]) => `${label}: ${value}`)
.join("\n")
: "";
const reviews = request.command.kind === "reviews" && delivery.reviews.length ? `\n${delivery.reviews.map((review) => `- ${review.candidateId} | request ${review.mindRequestId} | revision ${review.modelRevision} | frontier ${review.frontierItemId}`).join("\n")}` : "";
const decision = request.command.kind === "review" && delivery.reviewCandidateId ? `\nCandidate ${delivery.reviewCandidateId}: ${delivery.reviewDecision}` : "";
return `Epiphany ${command}: ${headline}.${detail}${statuses ? `\n${statuses}` : ""}${reviews}${decision}\nBifrost reported this terminal result; VoidBot did not execute or inspect Epiphany state.`;
}
function renderStatusV2(value: EpiphanyOperatorStatusV2): string {
const provider = (label: string, p: EpiphanyOperatorStatusProviderV2) => (p.availability === "unavailable" ? `${label}: unavailable (${bounded(p.unavailableReason)})` : `${label}: authenticated-current | ${bounded(p.state!)} | ${bounded(p.reasonCode!)}`);
return [`Epiphany status: Completed (observed).`, `Deployment: ${bounded(value.releaseId)} | commit ${value.sourceCommit} | ${bounded(value.deploymentId)}`, `Resident: ${bounded(value.residentStatus)} | Brake: ${bounded(value.brakeStatus)}`, `Pressure: ${value.pressureCount} | Reviews: ${value.pendingReviewCount}`, `Provider set: ${value.providerSetStatus}`, provider("Epiphany", value.providers[0]), provider("Bifrost", value.providers[1]), `Bifrost reported this terminal result; VoidBot did not execute or inspect Epiphany state.`].join("\n");
}
function bounded(value: string): string {
return value.length <= 96 ? value : `${value.slice(0, 95)}…`;
}
function validateStatusV2(value: unknown): asserts value is EpiphanyOperatorStatusV2 {
const keys = ["schemaVersion", "releaseId", "releaseWitnessSha256", "sourceCommit", "deploymentId", "coordinatorSnapshot", "coordinatorState", "coordinatorAction", "brakeStatus", "residentStatus", "pressureCount", "pendingReviewCount", "providerSetStatus", "providers", "privateStateExposed"];
if (!isRecord(value) || Object.keys(value).sort().join("\0") !== keys.sort().join("\0")) throw new Error("statusV2 has an inexact field set");
if (value.schemaVersion !== "epiphany.operator.status.v2" || value.privateStateExposed !== false) throw new Error("statusV2 schema or privacy invariant is invalid");
for (const k of ["releaseId", "deploymentId", "coordinatorSnapshot", "coordinatorState", "coordinatorAction", "brakeStatus", "residentStatus"]) {
if (typeof value[k] !== "string" || !value[k] || value[k].length > 256) throw new Error(`statusV2 ${k} is invalid`);
}
if (!SHA256.test(value.releaseWitnessSha256) || typeof value.sourceCommit !== "string" || !/^[0-9a-f]{40}$/.test(value.sourceCommit)) throw new Error("statusV2 release lineage is invalid");
for (const k of ["pressureCount", "pendingReviewCount"]) if (!Number.isSafeInteger(value[k]) || value[k] < 0 || value[k] > 1_000_000) throw new Error(`statusV2 ${k} is invalid`);
if (value.providerSetStatus !== "complete-authenticated" && value.providerSetStatus !== "incomplete") throw new Error("statusV2 provider set is invalid");
if (!Array.isArray(value.providers) || value.providers.length !== 2) throw new Error("statusV2 requires exactly two providers");
validateStatusProvider(value.providers[0], "yggdrasil-epiphany", "epiphany.cultnet-rudp-runtime-health", true);
validateStatusProvider(value.providers[1], "yggdrasil-bifrost-persona-feedback", "bifrost.cultnet-rudp-persona-feedback-health", false);
if (value.providers.every((p) => p.availability === "authenticated-current") !== (value.providerSetStatus === "complete-authenticated")) throw new Error("statusV2 provider set completeness is false");
}
function validateStatusProvider(value: unknown, daemon: string, contract: string, lineage: boolean): asserts value is EpiphanyOperatorStatusProviderV2 {
const keys = ["daemonId", "healthContract", "availability", "unavailableReason", "state", "reasonCode", "providerObservedAtUnixMillis", "evaluatedAtUnixMillis", "expiresAtUnixMillis", "releaseId", "releaseWitnessSha256", "sourceCommit", "deploymentId", "projectionSha256"];
if (!isRecord(value) || Object.keys(value).sort().join("\0") !== keys.sort().join("\0")) throw new Error("statusV2 provider has an inexact field set");
if (value.daemonId !== daemon || value.healthContract !== contract) throw new Error("statusV2 provider policy mismatch");
if (value.availability !== "authenticated-current" && value.availability !== "unavailable") throw new Error("statusV2 provider availability is invalid");
if (typeof value.unavailableReason !== "string" || value.unavailableReason.length > 256) throw new Error("statusV2 unavailable reason is invalid");
const optional = ["state", "reasonCode", "releaseId", "sourceCommit", "deploymentId"] as const;
for (const k of optional) if (value[k] !== null && (typeof value[k] !== "string" || !value[k] || value[k].length > 256)) throw new Error(`statusV2 provider ${k} is invalid`);
for (const k of ["providerObservedAtUnixMillis", "evaluatedAtUnixMillis", "expiresAtUnixMillis"] as const) if (value[k] !== null && (!Number.isSafeInteger(value[k]) || value[k] < 0)) throw new Error(`statusV2 provider ${k} is invalid`);
for (const k of ["releaseWitnessSha256", "projectionSha256"] as const) if (value[k] !== null && !SHA256.test(value[k])) throw new Error(`statusV2 provider ${k} is invalid`);
if (value.sourceCommit !== null && !/^[0-9a-f]{40}$/.test(value.sourceCommit)) throw new Error("statusV2 provider commit is invalid");
const observed = [...optional, "providerObservedAtUnixMillis", "evaluatedAtUnixMillis", "expiresAtUnixMillis", "releaseWitnessSha256", "projectionSha256"] as const;
if (value.availability === "unavailable") {
if (!value.unavailableReason || observed.some((k) => value[k] !== null)) throw new Error("unavailable provider carries observed state");
} else {
if (value.unavailableReason || ["state", "reasonCode", "providerObservedAtUnixMillis", "evaluatedAtUnixMillis", "expiresAtUnixMillis", "projectionSha256"].some((k) => value[k] === null)) throw new Error("authenticated provider lacks bounded state");
if (lineage) {
if (["releaseId", "releaseWitnessSha256", "sourceCommit", "deploymentId"].some((k) => value[k] === null)) throw new Error("Epiphany provider lacks lineage");
} else if (["releaseId", "releaseWitnessSha256", "sourceCommit", "deploymentId"].some((k) => value[k] !== null)) throw new Error("Bifrost provider claims Epiphany lineage");
}
}
function validateReviewSummary(value: unknown): void {
const keys = ["mindRequestId", "candidateId", "candidateSha256", "modelRevision", "modelHash", "frontierItemId", "requestedAt"];
if (!isRecord(value) || Object.keys(value).sort().join("\0") !== keys.sort().join("\0")) throw new Error("review summary has an inexact field set");
for (const key of ["mindRequestId", "candidateId", "frontierItemId"] as const) if (!required(value[key], key) || value[key].length > 256) throw new Error(`review summary ${key} is invalid`);
for (const key of ["candidateSha256", "modelHash"] as const) if (!/^[0-9a-f]{64}$/.test(value[key])) throw new Error(`review summary ${key} is invalid`);
if (!Number.isSafeInteger(value.modelRevision) || value.modelRevision < 0) throw new Error("review summary modelRevision is invalid");
if (!Number.isFinite(Date.parse(value.requestedAt))) throw new Error("review summary requestedAt is invalid");
}
function requestDefinition(define: any): unknown {
return define({
type: EPIPHANY_OPERATOR_REQUEST_TYPE,
schemaName: EPIPHANY_OPERATOR_REQUEST_TYPE,
schemaId: EPIPHANY_OPERATOR_REQUEST_SCHEMA,
schemaVersion: EPIPHANY_OPERATOR_REQUEST_SCHEMA,
contentHash: EPIPHANY_OPERATOR_REQUEST_SCHEMA,
global: false,
name: "requestId",
schema: { parse: (v: unknown) => v },
});
}
function deliveryDefinition(define: any): unknown {
return define({
type: EPIPHANY_OPERATOR_DELIVERY_TYPE,
schemaName: EPIPHANY_OPERATOR_DELIVERY_TYPE,
schemaId: EPIPHANY_OPERATOR_DELIVERY_SCHEMA,
schemaVersion: EPIPHANY_OPERATOR_DELIVERY_SCHEMA,
contentHash: EPIPHANY_OPERATOR_DELIVERY_SCHEMA,
global: false,
name: "deliveryId",
schema: { parse: (v: unknown) => v },
});
}
function checkpointDefinition(define: any): unknown {
return define({
type: EPIPHANY_OPERATOR_CHECKPOINT_TYPE,
schemaName: EPIPHANY_OPERATOR_CHECKPOINT_TYPE,
schemaId: EPIPHANY_OPERATOR_CHECKPOINT_SCHEMA,
schemaVersion: EPIPHANY_OPERATOR_CHECKPOINT_SCHEMA,
contentHash: EPIPHANY_OPERATOR_CHECKPOINT_SCHEMA,
global: false,
name: "requestId",
schema: { parse: (v: unknown) => v },
});
}
function loadRuntime(config: { bifrostRoot: string; cultlibRoot?: string }): any {
const root = config.cultlibRoot ?? resolve(config.bifrostRoot, "..", "CultLib");
const mesh = resolve(root, "packages", "cultmesh-ts", "package.json");
const cache = resolve(root, "packages", "cultcache-ts", "package.json");
return {
CultMesh: createRequire(mesh)("cultmesh-ts").CultMesh,
defineDocumentType: createRequire(cache)("cultcache-ts").defineDocumentType,
};
}
function unwrap(value: unknown): any {
const record = value as { value?: unknown } | undefined;
return Array.isArray(value) ? value[0] : (record?.value ?? value);
}
function stable(value: unknown): string {
return JSON.stringify(value, (_k, v) => (v instanceof Uint8Array ? Buffer.from(v).toString("hex") : v));
}
function hashStable(value: unknown): string {
return `sha256-${createHash("sha256").update(stable(value)).digest("hex")}`;
}
function isRecord(value: unknown): value is Record<string, any> {
return !!value && typeof value === "object" && !Array.isArray(value);
}
function required(value: string, label: string): string {
const text = value?.trim();
if (!text) throw new Error(`${label} is required`);
return text;
}
function boundedError(error: unknown): string {
return (error instanceof Error ? error.message : String(error)).slice(0, 512);
}

View file

@ -1,207 +0,0 @@
import { createRequire } from "node:module";
import { resolve } from "node:path";
export const EPIPHANY_OPERATOR_REQUEST_TYPE = "voidbot.discord.epiphany_operator_request";
export const EPIPHANY_OPERATOR_REQUEST_SCHEMA = "voidbot.discord.epiphany_operator_request.v1";
export const EPIPHANY_OPERATOR_RUNTIME_ID = "epiphany-yggdrasil";
const MAX_REASON_LENGTH = 500;
const MAX_OBJECTIVE_LENGTH = 2_000;
const REQUEST_LIFETIME_MS = 60_000;
export type EpiphanyOperatorCommand =
| { kind: "status" }
| { kind: "sleep"; reason: string }
| { kind: "wake" }
| { kind: "directive"; objective: string }
| { kind: "reviews" }
| {
kind: "review";
mindRequestId: string;
candidateId: string;
candidateSha256: string;
expectedModelRevision: number;
expectedModelHash: string;
decision: "adopt" | "refuse" | "hold";
};
export interface EpiphanyOperatorRequestInput {
interactionId: string;
actorDiscordId: string;
guildId: string;
channelId: string;
command: EpiphanyOperatorCommand;
issuedAt?: string;
}
export interface EpiphanyOperatorRequestConfig {
storePath: string;
bifrostRoot: string;
producerRuntimeId: string;
cultlibRoot?: string;
}
export interface EpiphanyOperatorRequestDocument {
schemaName: typeof EPIPHANY_OPERATOR_REQUEST_TYPE;
schemaVersion: typeof EPIPHANY_OPERATOR_REQUEST_SCHEMA;
requestId: string;
commandId: string;
nonce: string;
sourceEventId: string;
sourceActorDiscordId: string;
discordGuildId: string;
discordChannelId: string;
discordMessageId: string;
targetRuntimeId: typeof EPIPHANY_OPERATOR_RUNTIME_ID;
issuedAt: string;
expiresAt: string;
producerId: "voidbot";
producerRuntimeId: string;
authorityClass: "operator_request_only";
status: "pending";
command: EpiphanyOperatorCommand;
}
interface OperatorRequestNode {
put: (definition: unknown, key: string, value: unknown) => Promise<void>;
get?: (definition: unknown, key: string) => unknown;
flush?: () => Promise<void>;
cache?: { pullAllBackingStores?: () => Promise<void> };
}
export function buildEpiphanyOperatorRequest(
input: EpiphanyOperatorRequestInput,
producerRuntimeId: string,
): EpiphanyOperatorRequestDocument {
const interactionId = boundedText(input.interactionId, "interaction id", 128);
const actorDiscordId = boundedText(input.actorDiscordId, "actor Discord id", 128);
const guildId = boundedText(input.guildId, "Discord guild id", 128);
const channelId = boundedText(input.channelId, "Discord channel id", 128);
const runtime = boundedText(producerRuntimeId, "producer runtime id", 128);
const issuedAt = input.issuedAt ?? new Date().toISOString();
const issuedAtMillis = Date.parse(issuedAt);
if (!Number.isFinite(issuedAtMillis)) throw new Error("Epiphany operator request issuedAt must be RFC3339.");
const command = validateCommand(input.command);
return {
schemaName: EPIPHANY_OPERATOR_REQUEST_TYPE,
schemaVersion: EPIPHANY_OPERATOR_REQUEST_SCHEMA,
requestId: interactionId,
commandId: interactionId,
nonce: interactionId,
sourceEventId: interactionId,
sourceActorDiscordId: actorDiscordId,
discordGuildId: guildId,
discordChannelId: channelId,
discordMessageId: interactionId,
targetRuntimeId: EPIPHANY_OPERATOR_RUNTIME_ID,
issuedAt: new Date(issuedAtMillis).toISOString(),
expiresAt: new Date(issuedAtMillis + REQUEST_LIFETIME_MS).toISOString(),
producerId: "voidbot",
producerRuntimeId: runtime,
authorityClass: "operator_request_only",
status: "pending",
command,
};
}
export async function submitEpiphanyOperatorRequest(
input: EpiphanyOperatorRequestInput,
config: EpiphanyOperatorRequestConfig,
dependencies: { openNode?: () => Promise<OperatorRequestNode>; definition?: unknown } = {},
): Promise<EpiphanyOperatorRequestDocument> {
const request = buildEpiphanyOperatorRequest(input, config.producerRuntimeId);
const definition = dependencies.definition ?? loadDefinition(config);
const node = await (dependencies.openNode ?? (() => openNode(config, definition)))();
await node.cache?.pullAllBackingStores?.();
const existing = unwrap(node.get?.(definition, request.requestId));
if (existing && stable(existing) !== stable(request)) {
throw new Error(`Epiphany operator request ${request.requestId} already exists with different immutable content.`);
}
if (!existing) await node.put(definition, request.requestId, request);
await node.flush?.();
return request;
}
function validateCommand(command: EpiphanyOperatorCommand): EpiphanyOperatorCommand {
if (!command || typeof command !== "object") throw new Error("Epiphany operator command is required.");
switch (command.kind) {
case "status":
return { kind: "status" };
case "sleep":
return { kind: "sleep", reason: boundedText(command.reason, "sleep reason", MAX_REASON_LENGTH) };
case "wake":
return { kind: "wake" };
case "directive":
return { kind: "directive", objective: boundedText(command.objective, "directive objective", MAX_OBJECTIVE_LENGTH) };
case "reviews":
return { kind: "reviews" };
case "review": {
const candidateSha256 = sha256(command.candidateSha256, "candidate sha256");
const expectedModelHash = sha256(command.expectedModelHash, "expected model hash");
if (!Number.isSafeInteger(command.expectedModelRevision) || command.expectedModelRevision < 0) {
throw new Error("expected model revision must be a non-negative safe integer.");
}
if (!["adopt", "refuse", "hold"].includes(command.decision)) throw new Error("review decision is invalid.");
return {
kind: "review",
mindRequestId: boundedText(command.mindRequestId, "Mind request id", 256),
candidateId: boundedText(command.candidateId, "candidate id", 256),
candidateSha256,
expectedModelRevision: command.expectedModelRevision,
expectedModelHash,
decision: command.decision,
};
}
default:
throw new Error("Unsupported Epiphany operator command.");
}
}
function sha256(value: string, label: string): string {
const normalized = value?.trim();
if (!/^[0-9a-f]{64}$/.test(normalized)) throw new Error(`${label} must be 64 lowercase hexadecimal characters.`);
return normalized;
}
function boundedText(value: string, label: string, maxLength: number): string {
const normalized = value?.trim();
if (!normalized) throw new Error(`${label} is required.`);
if (normalized.length > maxLength) throw new Error(`${label} exceeds ${maxLength} characters.`);
return normalized;
}
function loadDefinition(config: EpiphanyOperatorRequestConfig): unknown {
const { defineDocumentType } = loadRuntime(config);
return defineDocumentType({
type: EPIPHANY_OPERATOR_REQUEST_TYPE,
schemaName: EPIPHANY_OPERATOR_REQUEST_TYPE,
schemaId: EPIPHANY_OPERATOR_REQUEST_SCHEMA,
schemaVersion: EPIPHANY_OPERATOR_REQUEST_SCHEMA,
contentHash: EPIPHANY_OPERATOR_REQUEST_SCHEMA,
global: false,
name: "requestId",
schema: { parse(value: unknown) { return value; } },
});
}
function openNode(config: EpiphanyOperatorRequestConfig, definition: unknown): Promise<OperatorRequestNode> {
return loadRuntime(config).CultMesh.createNode(config.storePath, { documents: [definition] });
}
function loadRuntime(config: EpiphanyOperatorRequestConfig): any {
const root = config.cultlibRoot ?? resolve(config.bifrostRoot, "..", "CultLib");
const meshPath = resolve(root, "packages", "cultmesh-ts", "package.json");
const cachePath = resolve(root, "packages", "cultcache-ts", "package.json");
return {
CultMesh: createRequire(meshPath)("cultmesh-ts").CultMesh,
defineDocumentType: createRequire(cachePath)("cultcache-ts").defineDocumentType,
};
}
function unwrap(value: unknown): unknown {
const record = value as { value?: unknown } | undefined;
return Array.isArray(value) ? value[0] : record?.value ?? value;
}
function stable(value: unknown): string {
return JSON.stringify(value, (_key, current) => current instanceof Uint8Array ? Buffer.from(current).toString("hex") : current);
}

View file

@ -28,5 +28,3 @@ export * from "./persona-state-domain";
export * from "./persona-state-service";
export * from "./bifrost-discord-command";
export * from "./persona-feedback-observation";
export * from "./epiphany-operator-request";
export * from "./epiphany-operator-delivery";

View file

@ -1,593 +0,0 @@
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { createRequire } from "node:module";
import { join, resolve } from "node:path";
import { buildEpiphanyOperatorRequest, epiphanyOperatorRequestPayloadSha256, processEpiphanyOperatorDelivery, consumeEpiphanyOperatorDeliveries, registerEpiphanyOperatorInteraction, submitEpiphanyOperatorRequest, validateDelivery, type EpiphanyOperatorDeliveryDocument, type EpiphanyOperatorDeliveryCheckpoint } from "../packages/core/src/index";
async function main(): Promise<void> {
const request = buildEpiphanyOperatorRequest(
{
interactionId: "interaction-1",
actorDiscordId: "owner-1",
guildId: "guild-1",
channelId: "channel-1",
command: { kind: "sleep", reason: "bank the fire" },
issuedAt: "2026-07-19T12:00:00.000Z",
},
"voidbot-yggdrasil",
);
const digest = epiphanyOperatorRequestPayloadSha256(request);
assert.match(digest, /^sha256-[0-9a-f]{64}$/);
assert.notEqual(
digest,
epiphanyOperatorRequestPayloadSha256({
...request,
discordGuildId: "other",
}),
);
assert.notEqual(
digest,
epiphanyOperatorRequestPayloadSha256({
...request,
command: { kind: "wake" },
}),
);
const completed: EpiphanyOperatorDeliveryDocument = {
schemaVersion: "bifrost.discord.epiphany_operator_delivery.v1",
deliveryId: request.requestId,
requestId: request.requestId,
requestPayloadSha256: digest,
commandId: request.commandId,
discordGuildId: request.discordGuildId,
discordChannelId: request.discordChannelId,
discordInteractionId: request.sourceEventId,
targetRuntimeId: "epiphany-yggdrasil",
status: "completed",
disposition: "observed",
failureCode: "",
detail: "sleep accepted",
operatorStatus: "sleeping",
stateStatus: "banked",
coordinatorAction: "none",
brakeStatus: "engaged",
sealedResultPayloadSha256: `sha256-${"a".repeat(64)}`,
executorSignatureSha256: `sha256-${"b".repeat(64)}`,
resultProviderIdentityId: "bifrost-yggdrasil",
reviews: [],
reviewCandidateId: "",
reviewDecision: "",
statusV2: null,
recordedAt: "2026-07-19T12:00:01.000Z",
privateStateExposed: false,
};
assert.equal(validateDelivery(completed).status, "completed");
const refused: EpiphanyOperatorDeliveryDocument = {
...completed,
status: "refused",
disposition: "",
failureCode: "brakes_engaged",
detail: "refused",
operatorStatus: "",
stateStatus: "",
coordinatorAction: "",
brakeStatus: "",
sealedResultPayloadSha256: "",
executorSignatureSha256: "",
resultProviderIdentityId: "",
reviews: [],
reviewCandidateId: "",
reviewDecision: "",
};
assert.equal(validateDelivery(refused).status, "refused");
function rejects(change: Record<string, unknown>, pattern: RegExp): void {
assert.throws(() => validateDelivery({ ...completed, ...change }), pattern);
}
rejects({ privateStateExposed: true }, /private state/);
rejects({ status: "pending" }, /terminal/);
rejects({ detail: "x".repeat(513) }, /detail/);
rejects({ operatorStatus: "x".repeat(513) }, /operatorStatus/);
rejects({ requestPayloadSha256: "raw-payload" }, /digest/);
rejects({ targetRuntimeId: "epiphany-nightwing" }, /runtime/);
rejects({ deliveryId: "collision" }, /identity/);
rejects({ executorSignatureSha256: "signature-bytes" }, /sealed bindings/);
rejects({ resultProviderIdentityId: "" }, /resultProviderIdentityId|sealed bindings/);
rejects({ surprisePrivatePayload: "secret" }, /field set/);
rejects(
{
reviews: [
{
mindRequestId: "m",
candidateId: "c",
candidateSha256: "1".repeat(64),
modelRevision: 1,
modelHash: "2".repeat(64),
frontierItemId: "f",
requestedAt: "2026-07-19T12:00:00Z",
proposalText: "private",
},
],
},
/inexact field set/,
);
rejects(
{
reviews: Array.from({ length: 11 }, () => ({
mindRequestId: "m",
candidateId: "c",
candidateSha256: "1".repeat(64),
modelRevision: 1,
modelHash: "2".repeat(64),
frontierItemId: "f",
requestedAt: "2026-07-19T12:00:00Z",
})),
},
/at most ten/,
);
assert.throws(() => validateDelivery({ ...refused, brakeStatus: "not empty" }), /completed-result bindings/);
assert.throws(() => validateDelivery({ ...refused, failureCode: "" }), /failureCode|failure code/);
const baseCheckpoint: EpiphanyOperatorDeliveryCheckpoint = {
schemaVersion: "voidbot.private.epiphany_operator_delivery_checkpoint.v0",
requestId: request.requestId,
applicationId: "app-1",
interactionToken: "private-token",
discordGuildId: request.discordGuildId,
discordChannelId: request.discordChannelId,
discordInteractionId: request.sourceEventId,
targetRuntimeId: "epiphany-yggdrasil",
state: "pending",
observedDeliverySha256: "",
respondedDeliverySha256: "",
attemptCount: 0,
lastError: "",
registeredAt: "2026-07-19T12:00:00.000Z",
updatedAt: "2026-07-19T12:00:00.000Z",
};
const statusRequest = buildEpiphanyOperatorRequest(
{
interactionId: "interaction-status",
actorDiscordId: "owner-1",
guildId: "guild-1",
channelId: "channel-1",
command: { kind: "status" },
issuedAt: "2026-07-19T12:00:00.000Z",
},
"voidbot-yggdrasil",
);
const unavailable = (daemonId: string, healthContract: string) => ({
daemonId,
healthContract,
availability: "unavailable" as const,
unavailableReason: "required-provider-record-missing",
state: null,
reasonCode: null,
providerObservedAtUnixMillis: null,
evaluatedAtUnixMillis: null,
expiresAtUnixMillis: null,
releaseId: null,
releaseWitnessSha256: null,
sourceCommit: null,
deploymentId: null,
projectionSha256: null,
});
const statusDelivery: EpiphanyOperatorDeliveryDocument = {
...completed,
deliveryId: statusRequest.requestId,
requestId: statusRequest.requestId,
commandId: statusRequest.commandId,
discordInteractionId: statusRequest.sourceEventId,
requestPayloadSha256: epiphanyOperatorRequestPayloadSha256(statusRequest),
statusV2: {
schemaVersion: "epiphany.operator.status.v2",
releaseId: "release-7",
releaseWitnessSha256: `sha256-${"7".repeat(64)}`,
sourceCommit: "8".repeat(40),
deploymentId: "deployment-9",
coordinatorSnapshot: "sleeping",
coordinatorState: "ready",
coordinatorAction: "none",
brakeStatus: "engaged",
residentStatus: "idle",
pressureCount: 3,
pendingReviewCount: 2,
providerSetStatus: "incomplete",
providers: [unavailable("yggdrasil-epiphany", "epiphany.cultnet-rudp-runtime-health"), unavailable("yggdrasil-bifrost-persona-feedback", "bifrost.cultnet-rudp-persona-feedback-health")],
privateStateExposed: false,
},
};
assert.equal(validateDelivery(statusDelivery).statusV2?.providerSetStatus, "incomplete");
for (const hostile of [
{
...statusDelivery,
statusV2: { ...statusDelivery.statusV2!, privateKey: "secret" },
},
{
...statusDelivery,
statusV2: { ...statusDelivery.statusV2!, privateStateExposed: true },
},
{
...statusDelivery,
statusV2: {
...statusDelivery.statusV2!,
residentStatus: "x".repeat(257),
},
},
{
...statusDelivery,
statusV2: {
...statusDelivery.statusV2!,
providerSetStatus: "complete-authenticated",
},
},
{
...statusDelivery,
statusV2: {
...statusDelivery.statusV2!,
providers: [...statusDelivery.statusV2!.providers].reverse(),
},
},
])
assert.throws(() => validateDelivery(hostile));
let statusText = "",
statusCheckpoint = {
...baseCheckpoint,
requestId: statusRequest.requestId,
discordInteractionId: statusRequest.sourceEventId,
};
assert.equal(
await processEpiphanyOperatorDelivery(
statusDelivery,
statusRequest,
statusCheckpoint,
async (_a, _t, text) => {
statusText = text;
},
async (next) => {
statusCheckpoint = next;
},
),
"responded",
);
assert.match(statusText, /Deployment: release-7 \| commit [8]{40} \| deployment-9/);
assert.match(statusText, /Resident: idle \| Brake: engaged/);
assert.match(statusText, /Pressure: 3 \| Reviews: 2/);
assert.match(statusText, /Provider set: incomplete/);
assert.match(statusText, /Epiphany: unavailable \(required-provider-record-missing\)/);
assert.match(statusText, /Bifrost: unavailable \(required-provider-record-missing\)/);
assert.doesNotMatch(statusText, /signature|sha256|private|path|key/i);
assert.ok(statusText.length < 2000);
const currentProvider = (base: ReturnType<typeof unavailable>, state: string, withLineage: boolean) => ({
...base,
availability: "authenticated-current" as const,
unavailableReason: "",
state,
reasonCode: "healthy",
providerObservedAtUnixMillis: 1,
evaluatedAtUnixMillis: 2,
expiresAtUnixMillis: 3,
releaseId: withLineage ? "release-7" : null,
releaseWitnessSha256: withLineage ? `sha256-${"7".repeat(64)}` : null,
sourceCommit: withLineage ? "8".repeat(40) : null,
deploymentId: withLineage ? "deployment-9" : null,
projectionSha256: `sha256-${"9".repeat(64)}`,
});
const completeDelivery: EpiphanyOperatorDeliveryDocument = {
...statusDelivery,
statusV2: {
...statusDelivery.statusV2!,
providerSetStatus: "complete-authenticated",
providers: [currentProvider(unavailable("yggdrasil-epiphany", "epiphany.cultnet-rudp-runtime-health"), "serving", true), currentProvider(unavailable("yggdrasil-bifrost-persona-feedback", "bifrost.cultnet-rudp-persona-feedback-health"), "ready", false)],
},
};
let completeText = "",
completeCheckpoint = {
...baseCheckpoint,
requestId: statusRequest.requestId,
discordInteractionId: statusRequest.sourceEventId,
};
assert.equal(
await processEpiphanyOperatorDelivery(
completeDelivery,
statusRequest,
completeCheckpoint,
async (_a, _t, text) => {
completeText = text;
},
async (next) => {
completeCheckpoint = next;
},
),
"responded",
);
assert.match(completeText, /Provider set: complete-authenticated/);
assert.match(completeText, /Epiphany: authenticated-current \| serving \| healthy/);
assert.match(completeText, /Bifrost: authenticated-current \| ready \| healthy/);
assert.doesNotMatch(completeText, /sha256|signature|private|path|key/i);
assert.equal(
await processEpiphanyOperatorDelivery(
{ ...statusDelivery, statusV2: null },
statusRequest,
{
...baseCheckpoint,
requestId: statusRequest.requestId,
discordInteractionId: statusRequest.sourceEventId,
},
async () => {
throw new Error("must not lower missing status");
},
async () => {},
),
"failed",
);
let current = baseCheckpoint;
let editCount = 0;
let failEdit = true;
const edit = async (_app: string, token: string, content: string): Promise<void> => {
assert.equal(token, "private-token");
assert.doesNotMatch(content, /signature|private-token|sha256-/i);
editCount += 1;
if (failEdit) throw new Error("temporary Discord failure");
};
const save = async (next: EpiphanyOperatorDeliveryCheckpoint): Promise<void> => {
current = next;
};
assert.equal(await processEpiphanyOperatorDelivery(completed, request, current, edit, save), "failed");
assert.equal(current.state, "pending");
assert.match(current.lastError, /temporary Discord failure/);
assert.ok(current.observedDeliverySha256);
failEdit = false;
assert.equal(await processEpiphanyOperatorDelivery(completed, request, current, edit, save), "responded");
assert.equal(current.state, "responded");
assert.equal(await processEpiphanyOperatorDelivery(completed, request, current, edit, save), "replayed");
assert.equal(editCount, 2, "a restart replay must not create another response");
for (const [field, value] of [
["commandId", "wrong"],
["discordGuildId", "wrong"],
["discordChannelId", "wrong"],
["discordInteractionId", "wrong"],
["targetRuntimeId", "epiphany-nightwing"],
["requestPayloadSha256", `sha256-${"c".repeat(64)}`],
] as const) {
let rejectedCheckpoint = { ...baseCheckpoint };
assert.equal(
await processEpiphanyOperatorDelivery(
{ ...completed, [field]: value },
request,
rejectedCheckpoint,
async () => {
throw new Error("must not edit");
},
async (next) => {
rejectedCheckpoint = next;
},
),
"failed",
);
assert.match(rejectedCheckpoint.lastError, /request|runtime|digest/);
}
let collisionCheckpoint = {
...baseCheckpoint,
observedDeliverySha256: `sha256-${"d".repeat(64)}`,
};
assert.equal(
await processEpiphanyOperatorDelivery(
completed,
request,
collisionCheckpoint,
async () => {
throw new Error("must not edit");
},
async (next) => {
collisionCheckpoint = next;
},
),
"failed",
);
assert.match(collisionCheckpoint.lastError, /collision/);
const reviewRequest = buildEpiphanyOperatorRequest(
{
interactionId: "interaction-review",
actorDiscordId: "owner-1",
guildId: "guild-1",
channelId: "channel-1",
command: { kind: "reviews" },
issuedAt: "2026-07-19T12:00:00.000Z",
},
"voidbot-yggdrasil",
);
const reviewDelivery: EpiphanyOperatorDeliveryDocument = {
...completed,
deliveryId: reviewRequest.requestId,
requestId: reviewRequest.requestId,
commandId: reviewRequest.commandId,
discordInteractionId: reviewRequest.sourceEventId,
requestPayloadSha256: epiphanyOperatorRequestPayloadSha256(reviewRequest),
reviews: [
{
mindRequestId: "mind-1",
candidateId: "candidate-1",
candidateSha256: "1".repeat(64),
modelRevision: 7,
modelHash: "2".repeat(64),
frontierItemId: "frontier-1",
requestedAt: "2026-07-19T11:59:00Z",
},
],
};
let renderedReview = "";
let reviewCheckpoint = {
...baseCheckpoint,
requestId: reviewRequest.requestId,
discordInteractionId: reviewRequest.sourceEventId,
};
assert.equal(
await processEpiphanyOperatorDelivery(
reviewDelivery,
reviewRequest,
reviewCheckpoint,
async (_app, _token, content) => {
renderedReview = content;
},
async (next) => {
reviewCheckpoint = next;
},
),
"responded",
);
assert.match(renderedReview, /candidate-1.*request mind-1.*revision 7.*frontier frontier-1/);
assert.doesNotMatch(renderedReview, /proposal|private|sha256/i);
let substitutedCheckpoint = { ...baseCheckpoint };
assert.equal(
await processEpiphanyOperatorDelivery(
{ ...completed, reviews: reviewDelivery.reviews },
request,
substitutedCheckpoint,
async () => {
throw new Error("must not render substituted review state");
},
async (next) => {
substitutedCheckpoint = next;
},
),
"failed",
);
assert.match(substitutedCheckpoint.lastError, /non-review/);
const decisionRequest = buildEpiphanyOperatorRequest(
{
interactionId: "interaction-decision",
actorDiscordId: "owner-1",
guildId: "guild-1",
channelId: "channel-1",
command: {
kind: "review",
mindRequestId: "mind-1",
candidateId: "candidate-1",
candidateSha256: "1".repeat(64),
expectedModelRevision: 7,
expectedModelHash: "2".repeat(64),
decision: "hold",
},
issuedAt: "2026-07-19T12:00:00.000Z",
},
"voidbot-yggdrasil",
);
const decisionDelivery: EpiphanyOperatorDeliveryDocument = {
...completed,
deliveryId: decisionRequest.requestId,
requestId: decisionRequest.requestId,
commandId: decisionRequest.commandId,
discordInteractionId: decisionRequest.sourceEventId,
requestPayloadSha256: epiphanyOperatorRequestPayloadSha256(decisionRequest),
reviewCandidateId: "candidate-1",
reviewDecision: "hold",
};
let decisionCheckpoint = {
...baseCheckpoint,
requestId: decisionRequest.requestId,
discordInteractionId: decisionRequest.sourceEventId,
};
assert.equal(
await processEpiphanyOperatorDelivery(
{ ...decisionDelivery, reviewCandidateId: "candidate-2" },
decisionRequest,
decisionCheckpoint,
async () => {
throw new Error("must not render substituted decision");
},
async (next) => {
decisionCheckpoint = next;
},
),
"failed",
);
assert.match(decisionCheckpoint.lastError, /exact candidate and decision/);
const temp = await mkdtemp(join(tmpdir(), "voidbot-epiphany-delivery-"));
try {
const bifrostRoot = resolve("../Bifrost");
const cultlibRoot = resolve("../CultLib");
const stores = {
requestStorePath: join(temp, "requests.cc"),
deliveryStorePath: join(temp, "deliveries.cc"),
checkpointStorePath: join(temp, "checkpoints.cc"),
bifrostRoot,
cultlibRoot,
};
await registerEpiphanyOperatorInteraction(
{
requestId: request.requestId,
applicationId: "app-1",
interactionToken: "private-token",
guildId: request.discordGuildId,
channelId: request.discordChannelId,
registeredAt: request.issuedAt,
},
stores,
);
await submitEpiphanyOperatorRequest(
{
interactionId: request.requestId,
actorDiscordId: request.sourceActorDiscordId,
guildId: request.discordGuildId,
channelId: request.discordChannelId,
command: request.command,
issuedAt: request.issuedAt,
},
{
storePath: stores.requestStorePath,
bifrostRoot,
cultlibRoot,
producerRuntimeId: request.producerRuntimeId,
},
);
const cachePackage = resolve(cultlibRoot, "packages/cultcache-ts/package.json");
const meshPackage = resolve(cultlibRoot, "packages/cultmesh-ts/package.json");
const define = createRequire(cachePackage)("cultcache-ts").defineDocumentType;
const CultMesh = createRequire(meshPackage)("cultmesh-ts").CultMesh;
const deliveryDef = define({
type: "bifrost.discord.epiphany_operator_delivery",
schemaName: "bifrost.discord.epiphany_operator_delivery",
schemaId: completed.schemaVersion,
schemaVersion: completed.schemaVersion,
contentHash: completed.schemaVersion,
global: false,
name: "deliveryId",
schema: { parse: (value: unknown) => value },
});
const deliveryNode = await CultMesh.createNode(stores.deliveryStorePath, {
documents: [deliveryDef],
});
await deliveryNode.put(deliveryDef, completed.deliveryId, completed);
let integrationEdits = 0;
assert.deepEqual(
await consumeEpiphanyOperatorDeliveries(stores, async () => {
integrationEdits += 1;
}),
{ observed: 1, responded: 1, failed: 0 },
);
assert.deepEqual(
await consumeEpiphanyOperatorDeliveries(stores, async () => {
integrationEdits += 1;
}),
{ observed: 1, responded: 0, failed: 0 },
);
assert.equal(integrationEdits, 1);
} finally {
await rm(temp, { recursive: true, force: true });
}
console.log("Epiphany operator delivery smoke passed.");
}
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -1,122 +0,0 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import {
EPIPHANY_OPERATOR_REQUEST_SCHEMA,
EPIPHANY_OPERATOR_REQUEST_TYPE,
buildEpiphanyOperatorRequest,
submitEpiphanyOperatorRequest,
} from "../packages/core/src/epiphany-operator-request";
import { commandDefinitions, isExactDiscordOwner } from "../apps/bot/src/discord-bot-handlers";
async function main(): Promise<void> {
const owner = "owner-1";
assert.equal(isExactDiscordOwner(owner, owner), true);
assert.equal(isExactDiscordOwner("administrator-1", owner), false);
assert.equal(isExactDiscordOwner("tier-one-1", owner), false);
const epiphany = commandDefinitions.map((command) => command.toJSON()).find((command) => command.name === "epiphany");
assert.ok(epiphany, "slash command is registered");
assert.deepEqual(epiphany.options?.map((option) => option.name), ["status", "sleep", "wake", "direct", "reviews", "review"]);
const protocolPath = process.env.EPIPHANY_OPERATOR_PROTOCOL_FIXTURE
?? resolve("..", "EpiphanyAgent", ".epiphany-smoke", "operator-command-interop-rust", "protocol.json");
const protocol = JSON.parse(await readFile(protocolPath, "utf8"));
assert.equal(protocol.schemaVersion, "epiphany.operator_command.protocol_fixture.v1");
assert.equal(protocol.admissionSchemaVersion, "bifrost.operator_command.delivery.v1");
assert.equal(protocol.resultSchemaVersion, "epiphany.operator_command.result.v1");
assert.deepEqual(protocol.commands.map((command: { kind: string }) => command.kind), ["status", "sleep", "wake", "directive", "reviews", "review"]);
assert.deepEqual(protocol.reviewDecisions, ["adopt", "refuse", "hold"]);
const issuedAt = "2026-07-19T12:00:00.000Z";
const commands = [
{ kind: "status" } as const,
{ kind: "sleep", reason: "Operator is packing the workstation." } as const,
{ kind: "wake" } as const,
{ kind: "directive", objective: "Inspect the current domain map and propose the next bounded improvement." } as const,
{ kind: "reviews" } as const,
protocol.commands[5],
];
for (const [index, command] of commands.entries()) {
const id = `interaction-${index}`;
const request = buildEpiphanyOperatorRequest({
interactionId: id,
actorDiscordId: owner,
guildId: "guild-1",
channelId: "channel-1",
command,
issuedAt,
}, "voidbot-yggdrasil");
assert.equal(request.schemaName, EPIPHANY_OPERATOR_REQUEST_TYPE);
assert.equal(request.schemaVersion, EPIPHANY_OPERATOR_REQUEST_SCHEMA);
assert.equal(request.requestId, id);
assert.equal(request.commandId, id);
assert.equal(request.nonce, id);
assert.equal(request.sourceEventId, id);
assert.equal(request.discordMessageId, id);
assert.equal(request.targetRuntimeId, "epiphany-yggdrasil");
assert.equal(request.authorityClass, "operator_request_only");
assert.equal(Date.parse(request.expiresAt) - Date.parse(request.issuedAt), 60_000);
assert.deepEqual(Object.keys(request).sort(), [
"authorityClass", "command", "commandId", "discordChannelId", "discordGuildId",
"discordMessageId", "expiresAt", "issuedAt", "nonce", "producerId", "producerRuntimeId",
"requestId", "schemaName", "schemaVersion", "sourceActorDiscordId", "sourceEventId", "status",
"targetRuntimeId",
].sort());
}
const stored = new Map<string, unknown>();
const definition = {};
const openNode = async () => ({
get: (_definition: unknown, key: string) => stored.get(key),
put: async (_definition: unknown, key: string, value: unknown) => { stored.set(key, value); },
flush: async () => undefined,
cache: { pullAllBackingStores: async () => undefined },
});
const input = {
interactionId: "interaction-replay",
actorDiscordId: owner,
guildId: "guild-1",
channelId: "channel-1",
command: { kind: "wake" } as const,
issuedAt,
};
const config = { storePath: "unused.cc", bifrostRoot: "unused", producerRuntimeId: "voidbot-yggdrasil" };
await submitEpiphanyOperatorRequest(input, config, { definition, openNode });
await submitEpiphanyOperatorRequest(input, config, { definition, openNode });
await assert.rejects(
submitEpiphanyOperatorRequest({ ...input, command: { kind: "status" } }, config, { definition, openNode }),
/different immutable content/,
);
assert.throws(() => buildEpiphanyOperatorRequest({ ...input, command: { kind: "sleep", reason: "x".repeat(501) } }, "voidbot-yggdrasil"), /500/);
assert.throws(() => buildEpiphanyOperatorRequest({ ...input, command: { kind: "directive", objective: "x".repeat(2001) } }, "voidbot-yggdrasil"), /2000/);
const review = commands[5] as Extract<(typeof commands)[number], { kind: "review" }>;
assert.deepEqual(Object.keys(protocol.commands[5]).sort(), ["candidateId", "candidateSha256", "decision", "expectedModelHash", "expectedModelRevision", "kind", "mindRequestId"].sort());
assert.throws(() => buildEpiphanyOperatorRequest({ ...input, command: { ...review, candidateSha256: "0".repeat(63) } }, "voidbot-yggdrasil"), /64 lowercase/);
assert.throws(() => buildEpiphanyOperatorRequest({ ...input, command: { ...review, expectedModelRevision: -1 } }, "voidbot-yggdrasil"), /non-negative/);
assert.throws(() => buildEpiphanyOperatorRequest({ ...input, command: { ...review, decision: "approve" as "adopt" } }, "voidbot-yggdrasil"), /decision/);
const botSource = await readFile(resolve("apps/bot/src/discord-bot.ts"), "utf8");
const messageCreate = botSource.slice(botSource.indexOf("client.on(Events.MessageCreate"), botSource.indexOf("client.on(Events.MessageUpdate"));
assert.ok(messageCreate.includes("exportPersonaFeedbackWithRetry"), "ordinary addressed messages retain feedback export");
assert.ok(!messageCreate.includes("submitEpiphanyOperatorRequest"), "ordinary messages cannot submit operator requests");
console.log(JSON.stringify({
schemaVersion: EPIPHANY_OPERATOR_REQUEST_SCHEMA,
commands: ["status", "sleep", "wake", "direct", "reviews", "review"],
rustProtocolFixtureConsumed: true,
exactOwnerOnly: true,
ordinaryMessagesRemainFeedbackOnly: true,
localExecutionAuthorized: false,
mindAuthorityGranted: false,
handsAuthorityGranted: false,
releaseAuthorityGranted: false,
deploymentAuthorityGranted: false,
}, null, 2));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -33,8 +33,6 @@ constraints:
invariants:
- The recovery MCP organ is read-only and loopback-only. It may consume exact archives, VoidBot-owned vector collections, and the configured embedding provider; it cannot start Discord, worker-job, Persona, moderation, Bifrost, Idunn, or canon mutation paths.
- The `/epiphany` Discord edge is an exact-owner request producer only. Its closed status/sleep/wake/direct command family writes short-lived immutable documents to a dedicated Bifrost inbox; ordinary conversation remains feedback-only, and VoidBot gains no Epiphany state, Mind, Hands, release, deployment, argv, or local-execution authority.
- The `/epiphany` result edge consumes only Bifrost's frozen immutable terminal delivery schema, validates it against VoidBot's exact request and private Discord interaction checkpoint, and may only edit the original ephemeral response. It cannot inspect Epiphany state, synthesize execution truth, expose signatures/private state, mutate the Bifrost outbox, or retry consequences.
- Deployment follows one path: push the intended upstream commit, then let Idunn deploy VoidBot on Yggdrasil. Do not create, restore, or search for a local VoidBot deployment path.
- The map is canonical and slow-changing.
- Scratch is temporary and disposable.