Lower typed Epiphany Status v2 deliveries

This commit is contained in:
Meta Vens 2026-07-19 23:02:16 +01:00
commit a5cee67754
2 changed files with 798 additions and 225 deletions

View file

@ -3,25 +3,14 @@ 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";
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", "recordedAt", "privateStateExposed",
] as const;
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 {
@ -48,10 +37,45 @@ export interface EpiphanyOperatorDeliveryDocument {
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;
@ -84,7 +108,10 @@ 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[] };
cache: {
pullAllBackingStores?: () => Promise<void>;
getAll: (definition: unknown) => unknown[];
};
}
export interface EpiphanyOperatorDeliveryStoresConfig {
@ -104,13 +131,12 @@ export interface RegisterEpiphanyOperatorInteractionInput {
registeredAt?: string;
}
export async function registerEpiphanyOperatorInteraction(
input: RegisterEpiphanyOperatorInteractionInput,
config: Pick<EpiphanyOperatorDeliveryStoresConfig, "checkpointStorePath" | "bifrostRoot" | "cultlibRoot">,
): Promise<void> {
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;
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 = {
@ -122,8 +148,13 @@ export async function registerEpiphanyOperatorInteraction(
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,
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)) {
@ -133,21 +164,26 @@ export async function registerEpiphanyOperatorInteraction(
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 }> {
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[];
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;
let observed = 0;
let responded = 0;
let failed = 0;
for (const raw of deliveries.cache.getAll(deliveryDef)) {
observed += 1;
const candidate = unwrap(raw);
@ -159,54 +195,56 @@ export async function consumeEpiphanyOperatorDeliveries(
await checkpoints.put(checkpointDef, checkpoint.requestId, next);
await checkpoints.flush?.();
});
if (outcome === "responded") responded += 1; else if (outcome === "failed") failed += 1;
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"> {
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() };
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() });
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() });
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];
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" && typeof value[key] !== "string") throw new Error(`delivery ${key} must be a string`);
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");
@ -225,8 +263,9 @@ export function validateDelivery(value: unknown): EpiphanyOperatorDeliveryDocume
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 !== "") throw new Error("refused delivery carries completed-result bindings");
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;
}
@ -241,6 +280,9 @@ function validateBindings(delivery: EpiphanyOperatorDeliveryDocument, request: E
} 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");
}
@ -248,18 +290,69 @@ function renderDelivery(delivery: EpiphanyOperatorDeliveryDocument, request: Epi
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}` : "";
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}` : "";
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");
@ -269,13 +362,69 @@ function validateReviewSummary(value: unknown): void {
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); }
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

@ -4,166 +4,590 @@ 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";
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 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 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: "",
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");
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/);
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");
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",
};
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/);
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 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 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 });
}
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.");
console.log("Epiphany operator delivery smoke passed.");
}
void main().catch((error) => { console.error(error); process.exitCode = 1; });
void main().catch((error) => {
console.error(error);
process.exitCode = 1;
});