Move Persona scheduler state to CultCache

This commit is contained in:
Meta Vens 2026-07-16 00:27:01 +01:00
commit 567f0e0226
14 changed files with 213 additions and 37 deletions

View file

@ -9,6 +9,7 @@
"@voidbot/core": "0.1.0",
"@voidbot/rag": "0.1.0",
"@voidbot/shared": "0.1.0",
"cultcache-ts": "file:../../vendor/cultcache-ts",
"dotenv": "^16.4.0"
}
}

View file

@ -1,10 +1,19 @@
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import {
CultCache,
SingleFileMessagePackBackingStore,
defineDocumentType,
type CultCacheSchema,
} from "cultcache-ts";
import {
acknowledgeRepoFaceMentionInbox,
readRepoFaceMentionInbox,
REPO_FACE_HEARTBEAT_SCHEMA_VERSION,
resolveRepoFaceHeartbeatDebugProjectionPath,
resolveRepoFaceHeartbeatStatePath,
type RepoFacePendingMention,
} from "@voidbot/core";
@ -22,12 +31,39 @@ type PersistedStateCandidate = Omit<Partial<PersonaSchedulerState>, "participant
participants?: Array<Partial<InitiativeParticipant> & { nextReadyAt?: string }>;
};
const PERSONA_SCHEDULER_STATE_RECORD_KEY = "persona-scheduler";
const personaSchedulerStateDefinition = defineDocumentType<CultCacheSchema<PersonaSchedulerState>>({
type: "voidbot.persona_scheduler_state",
schemaName: "voidbot.persona_scheduler_state",
global: false,
name: () => PERSONA_SCHEDULER_STATE_RECORD_KEY,
schema: {
parse(input: unknown): PersonaSchedulerState {
return parseCurrentPersonaSchedulerState(input, "CultCache document");
},
},
});
export async function readPersonaSchedulerState(path: string, nowMs = Date.now()): Promise<PersonaSchedulerState> {
const canonicalPath = resolveRepoFaceHeartbeatStatePath(path);
if (await pathExists(canonicalPath)) {
const cache = createPersonaSchedulerStateCache(canonicalPath);
try {
await cache.pullAllBackingStores();
const state = cache.get(personaSchedulerStateDefinition, PERSONA_SCHEDULER_STATE_RECORD_KEY);
if (!state) throw new Error("canonical scheduler record is missing");
return mergeMentionInbox(canonicalPath, state);
} catch (error) {
throw new Error(`Persona scheduler CultCache state at ${canonicalPath} is malformed; refusing to replace it with empty state.`, { cause: error });
}
}
const legacyPath = resolveRepoFaceHeartbeatDebugProjectionPath(canonicalPath);
let raw: string;
try {
raw = await readFile(path, "utf8");
raw = await readFile(legacyPath, "utf8");
} catch (error) {
if (isNodeError(error, "ENOENT")) return mergeMentionInbox(path, newPersonaSchedulerState());
if (isNodeError(error, "ENOENT")) return mergeMentionInbox(canonicalPath, newPersonaSchedulerState());
throw error;
}
@ -35,43 +71,60 @@ export async function readPersonaSchedulerState(path: string, nowMs = Date.now()
try {
parsed = JSON.parse(stripLeadingBom(raw)) as PersistedStateCandidate;
} catch (error) {
throw new Error(`Persona scheduler state at ${path} is malformed; refusing to replace it with empty state.`, { cause: error });
throw new Error(`Legacy Persona scheduler state at ${legacyPath} is malformed; refusing to replace it with empty state.`, { cause: error });
}
let migrated: PersonaSchedulerState;
if (parsed.schemaVersion === REPO_FACE_HEARTBEAT_SCHEMA_VERSION) {
if (!Array.isArray(parsed.participants)) {
throw new Error(`Persona scheduler state at ${path} has no participants array.`);
}
return mergeMentionInbox(path, {
schemaVersion: REPO_FACE_HEARTBEAT_SCHEMA_VERSION,
initiativeClock: finiteOr(parsed.initiativeClock, 0),
baseRecoveryMinutes: finiteOr(parsed.baseRecoveryMinutes, 10),
globalHeat: finiteOr(parsed.globalHeat, 1),
lastTickAt: parsed.lastTickAt,
participants: parsed.participants as InitiativeParticipant[],
history: Array.isArray(parsed.history) ? parsed.history : [],
pendingMentions: Array.isArray(parsed.pendingMentions)
? parsed.pendingMentions.filter(isRepoFacePendingMention)
: [],
});
migrated = parseCurrentPersonaSchedulerState(parsed, legacyPath);
} else if (Array.isArray(parsed.participants)) {
migrated = migrateLegacyHeartbeatState(parsed, nowMs);
} else {
throw new Error(`Legacy Persona scheduler state at ${legacyPath} has unsupported schema ${String(parsed.schemaVersion ?? "unknown")}.`);
}
if (Array.isArray(parsed.participants)) return mergeMentionInbox(path, migrateLegacyHeartbeatState(parsed, nowMs));
throw new Error(`Persona scheduler state at ${path} has unsupported schema ${String(parsed.schemaVersion ?? "unknown")}.`);
migrated.history.push({
type: "storage_migrated",
fromPath: legacyPath,
toPath: canonicalPath,
migratedAt: new Date(nowMs).toISOString(),
});
migrated.history = migrated.history.slice(-80);
await writeCanonicalPersonaSchedulerState(canonicalPath, migrated);
return mergeMentionInbox(canonicalPath, migrated);
}
export async function writePersonaSchedulerState(path: string, state: PersonaSchedulerState): Promise<void> {
const canonicalPath = resolveRepoFaceHeartbeatStatePath(path);
await writeCanonicalPersonaSchedulerState(canonicalPath, state);
await acknowledgeRepoFaceMentionInbox(canonicalPath, durableMentionIds(state));
await writeDebugProjection(resolveRepoFaceHeartbeatDebugProjectionPath(canonicalPath), state).catch(() => undefined);
}
async function writeCanonicalPersonaSchedulerState(path: string, state: PersonaSchedulerState): Promise<void> {
await mkdir(dirname(path), { recursive: true });
const cache = createPersonaSchedulerStateCache(path);
if (await pathExists(path)) await cache.pullAllBackingStores();
await cache.put(personaSchedulerStateDefinition, PERSONA_SCHEDULER_STATE_RECORD_KEY, state);
}
async function writeDebugProjection(path: string, state: PersonaSchedulerState): Promise<void> {
await mkdir(dirname(path), { recursive: true });
const temporaryPath = `${path}.${process.pid}.${Date.now()}.tmp`;
try {
await writeFile(temporaryPath, `${JSON.stringify(state, null, 2)}\n`, "utf8");
await rename(temporaryPath, path);
await acknowledgeRepoFaceMentionInbox(path, durableMentionIds(state));
} finally {
await rm(temporaryPath, { force: true }).catch(() => undefined);
}
}
function createPersonaSchedulerStateCache(path: string): CultCache {
return CultCache.builder()
.withDocumentType(personaSchedulerStateDefinition)
.withGenericStore(new SingleFileMessagePackBackingStore(path))
.build();
}
async function mergeMentionInbox(path: string, state: PersonaSchedulerState): Promise<PersonaSchedulerState> {
const known = durableMentionIds(state);
const incoming = await readRepoFaceMentionInbox(path);
@ -111,6 +164,35 @@ export function newPersonaSchedulerState(): PersonaSchedulerState {
};
}
function parseCurrentPersonaSchedulerState(input: unknown, source: string): PersonaSchedulerState {
if (!input || typeof input !== "object" || Array.isArray(input)) {
throw new Error(`Persona scheduler state from ${source} must be an object.`);
}
const parsed = input as PersistedStateCandidate;
if (parsed.schemaVersion !== REPO_FACE_HEARTBEAT_SCHEMA_VERSION) {
throw new Error(`Persona scheduler state from ${source} has unsupported schema ${String(parsed.schemaVersion ?? "unknown")}.`);
}
if (!Array.isArray(parsed.participants) || !parsed.participants.every(isInitiativeParticipant)) {
throw new Error(`Persona scheduler state from ${source} has invalid participants.`);
}
if (parsed.history !== undefined && (!Array.isArray(parsed.history) || !parsed.history.every(isRecord))) {
throw new Error(`Persona scheduler state from ${source} has invalid history.`);
}
if (parsed.pendingMentions !== undefined && (!Array.isArray(parsed.pendingMentions) || !parsed.pendingMentions.every(isRepoFacePendingMention))) {
throw new Error(`Persona scheduler state from ${source} has invalid pending mentions.`);
}
return {
schemaVersion: REPO_FACE_HEARTBEAT_SCHEMA_VERSION,
initiativeClock: finiteOr(parsed.initiativeClock, 0),
baseRecoveryMinutes: finiteOr(parsed.baseRecoveryMinutes, 10),
globalHeat: finiteOr(parsed.globalHeat, 1),
lastTickAt: typeof parsed.lastTickAt === "string" ? parsed.lastTickAt : undefined,
participants: parsed.participants,
history: (parsed.history ?? []) as Array<Record<string, unknown>>,
pendingMentions: (parsed.pendingMentions ?? []) as RepoFacePendingMention[],
};
}
function migrateLegacyHeartbeatState(parsed: PersistedStateCandidate, nowMs: number): PersonaSchedulerState {
const legacyBase = finiteOr(parsed.baseIntervalMinutes, 30);
const baseRecoveryMinutes = Math.max(5, legacyBase / 3);
@ -186,6 +268,39 @@ function isRepoFacePendingMention(value: unknown): value is RepoFacePendingMenti
);
}
function isInitiativeParticipant(value: unknown): value is InitiativeParticipant {
if (!isRecord(value)) return false;
return (
typeof value.identityId === "string" &&
["repo_face", "native_persona", "system_agent"].includes(String(value.participantKind)) &&
["repo_face_rumination", "void_moderation"].includes(String(value.turnKind)) &&
typeof value.repoName === "string" &&
typeof value.displayName === "string" &&
["active", "blocked", "withdrawn", "offscreen"].includes(String(value.status)) &&
[
value.initiativeSpeed,
value.reactionBias,
value.interruptThreshold,
value.currentLoad,
value.heat,
value.dynamicHeat,
value.responsePressure,
value.effectiveSpeed,
value.baseRecoveryMinutes,
value.nextTurnAt,
value.queuedCount,
].every((entry) => typeof entry === "number" && Number.isFinite(entry)) &&
Array.isArray(value.groups) &&
Array.isArray(value.responsePressureEvidence) &&
Array.isArray(value.semanticInterruptReceipts) &&
Array.isArray(value.constraints)
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
function finiteOr(value: unknown, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
}
@ -197,3 +312,13 @@ function stripLeadingBom(input: string): string {
function isNodeError(error: unknown, code: string): boolean {
return Boolean(error && typeof error === "object" && "code" in error && error.code === code);
}
async function pathExists(path: string): Promise<boolean> {
try {
await stat(path);
return true;
} catch (error) {
if (isNodeError(error, "ENOENT")) return false;
throw error;
}
}