Move Persona scheduler tick into daemon

This commit is contained in:
Meta Vens 2026-07-16 04:22:24 +01:00
commit f23bfbd8c9
11 changed files with 344 additions and 645 deletions

View file

@ -1,14 +1,10 @@
import "dotenv/config";
import { spawn } from "node:child_process";
import { resolve } from "node:path";
import { loadConfig } from "@voidbot/config";
import { runPersonaSchedulerTick } from "./persona-scheduler-runner.js";
const config = loadConfig();
const intervalMs = Math.max(1, config.repoFaceHeartbeats.intervalMinutes) * 60_000;
const turnEnginePath = resolve(process.cwd(), "scripts", "run-repo-face-heartbeats.ts");
let stopping = false;
let activeTick: Promise<void> | undefined;
let timer: NodeJS.Timeout | undefined;
@ -18,46 +14,17 @@ function runTick(): Promise<void> {
console.warn("Persona scheduler skipped a pulse because the previous turn-selection tick is still active.");
return activeTick;
}
activeTick = new Promise<void>((done) => {
const startedAt = new Date().toISOString();
const child = spawn(process.execPath, [turnEnginePath], {
cwd: process.cwd(),
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk: string) => { stdout += chunk; });
child.stderr.on("data", (chunk: string) => { stderr += chunk; });
child.once("error", (error) => {
console.error(`Persona scheduler tick failed to start: ${error.message}`);
});
child.once("close", (code, signal) => {
const output = stdout.trim();
if (code === 0) {
console.log(`Persona scheduler tick completed (started ${startedAt}).${output ? ` ${output}` : ""}`);
} else {
console.error(
`Persona scheduler tick failed (started ${startedAt}, code ${String(code)}, signal ${String(signal)}).${stderr.trim() ? ` ${stderr.trim()}` : ""}`,
);
}
done();
});
}).finally(() => {
activeTick = undefined;
});
const startedAt = new Date().toISOString();
activeTick = runPersonaSchedulerTick({ config })
.then((result) => { console.log(`Persona scheduler tick completed (started ${startedAt}). ${JSON.stringify(result)}`); })
.catch((error) => { console.error(`Persona scheduler tick failed (started ${startedAt}). ${error instanceof Error ? error.stack ?? error.message : String(error)}`); })
.finally(() => { activeTick = undefined; });
return activeTick;
}
function scheduleNext(): void {
if (stopping) return;
timer = setTimeout(async () => {
await runTick();
scheduleNext();
}, intervalMs);
timer = setTimeout(async () => { await runTick(); scheduleNext(); }, intervalMs);
}
async function shutdown(signal: string): Promise<void> {
@ -70,6 +37,5 @@ async function shutdown(signal: string): Promise<void> {
process.once("SIGINT", () => { void shutdown("SIGINT"); });
process.once("SIGTERM", () => { void shutdown("SIGTERM"); });
console.log(`Persona scheduler owns the resident ${config.repoFaceHeartbeats.intervalMinutes}-minute turn pulse.`);
console.log(`Persona scheduler owns the resident ${config.repoFaceHeartbeats.intervalMinutes}-minute observation pulse.`);
void runTick().then(scheduleNext);

View file

@ -383,7 +383,7 @@ export function recordStaleActiveTurnRecoveries(input: {
jobId: string;
requestMessageId?: string;
state: string;
updatedAt: string;
updatedAt?: string;
ageMinutes: number;
}>;
}): void {

View file

@ -0,0 +1,104 @@
import type { loadConfig } from "@voidbot/config";
import {
createStateStorage,
getRepoDiscordIdentityAllowedChannelIds,
type RepoDiscordIdentity,
type RepoFacePendingMention,
} from "@voidbot/core";
import type { InitiativeParticipant, ParticipantSpec as SchedulerParticipantSpec } from "./initiative-engine.js";
import type { PersonaStateObservation } from "./persona-state-source.js";
import { fetchChannelSnapshots, fetchRecentDiscordMessages } from "./turn-context-source.js";
import { readBifrostGovernanceDigest } from "./bifrost-governance-source.js";
import { coordinatePersonaMemoryTurn } from "./persona-memory-turn-coordinator.js";
import { readStoredPersonaHumanPronounGuidance } from "./persona-social-context-source.js";
import { projectNativePersonaBody } from "./persona-standard-state-projector.js";
import { readGlobalAgentDoctrine } from "./global-agent-doctrine-source.js";
import { assemblePersonaTurn } from "./persona-turn-assembler.js";
import { submitPersonaTurn } from "./turn-actuator.js";
import { launchVoidModerationTurn } from "./void-moderation-turn-actuator.js";
import { readRepoActivity } from "./repo-activity-source.js";
import { projectRepoActivityObservation } from "./repo-activity-projector.js";
import { buildPersonaChannelPlan, newestPendingMentionChannel, personaChannelSpeedMultiplier } from "./turn-routing.js";
export interface PersonaParticipantSpec extends SchedulerParticipantSpec {
identity?: RepoDiscordIdentity;
}
export interface PersonaTurnStartReceipt {
created: boolean;
activeJobId?: string;
requestMessageId?: string;
failureReason?: string;
}
export function buildPersonaParticipantSpecs(identities: RepoDiscordIdentity[], includeVoid: boolean): PersonaParticipantSpec[] {
return [
...(includeVoid ? [{ id: "void", participantKind: "system_agent" as const, turnKind: "void_moderation" as const, repoName: "VoidBot", displayName: "Void", allowedChannelIds: [], channelSpeedMultiplier: 1 }] : []),
...identities.map((identity) => ({
id: identity.id,
participantKind: identity.identityKind === "native_persona" ? "native_persona" as const : "repo_face" as const,
turnKind: "repo_face_rumination" as const,
repoName: identity.repoName,
displayName: identity.displayName,
allowedChannelIds: getRepoDiscordIdentityAllowedChannelIds(identity),
channelSpeedMultiplier: personaChannelSpeedMultiplier(identity),
identity,
})),
];
}
export function pendingMentionsForPersona(state: { pendingMentions: RepoFacePendingMention[] }, identityId: string): RepoFacePendingMention[] {
return state.pendingMentions.filter((mention) => mention.identityId === identityId).sort((left, right) => Date.parse(left.queuedAt) - Date.parse(right.queuedAt));
}
export function renderPersonaInitiativeAffinity(spec: PersonaParticipantSpec): string {
return [
`${spec.displayName} is the Persona steward of ${spec.repoName}.`,
spec.identity?.description,
...(spec.identity?.channelPermissions ?? []).flatMap((permission) => [permission.topic, permission.label, permission.posture]),
].filter((value): value is string => typeof value === "string" && value.trim().length > 0).join("\n");
}
export async function dispatchPersonaParticipantTurn(input: {
participant: InitiativeParticipant;
pendingMentions: RepoFacePendingMention[];
registryIdentities: RepoDiscordIdentity[];
config: ReturnType<typeof loadConfig>;
storage: Awaited<ReturnType<typeof createStateStorage>>;
queuedAt: string;
personaStateObservation?: PersonaStateObservation;
}): Promise<PersonaTurnStartReceipt> {
if (input.participant.turnKind === "void_moderation") return launchVoidModerationTurn({ queuedAt: input.queuedAt, storageRoot: input.config.storageRoot, pendingMentions: input.pendingMentions });
const identity = input.registryIdentities.find((entry) => entry.id === input.participant.identityId);
if (!identity) return { created: false, failureReason: `No registered Persona identity exists for ${input.participant.identityId}.` };
const channelPlan = buildPersonaChannelPlan(identity, input.config.repoFaceHeartbeats.defaultChannelId, newestPendingMentionChannel(input.pendingMentions));
const channelId = channelPlan.primaryChannelId;
if (!channelId) return { created: false, failureReason: "No CTB turn channel is configured for this Persona." };
const [recentMessages, channelSnapshots, bifrostDigest] = await Promise.all([
fetchRecentDiscordMessages({ botToken: input.config.botToken, channelId, limit: 15, ignoreBotMessages: channelId === input.config.bifrostDiscordChannelId }),
fetchChannelSnapshots({ botToken: input.config.botToken, channelIds: channelPlan.snapshotChannelIds, primaryChannelId: channelId, limit: 6, bifrostDiscordChannelId: input.config.bifrostDiscordChannelId }),
input.config.repoFaceBifrostEnabled && identity.identityKind !== "native_persona"
? readBifrostGovernanceDigest({ bifrostRoot: input.config.bifrostRoot, repoName: identity.repoName, agentIdentity: identity.id })
: Promise.resolve(undefined),
]);
const roomContext = { recentMessages, channelSnapshots };
const humanPronounGuidance = await readStoredPersonaHumanPronounGuidance({ config: input.config, ...roomContext });
const memoryContext = await coordinatePersonaMemoryTurn({ identity, config: input.config, registryIdentities: input.registryIdentities, ...roomContext, humanPronounGuidance, stateObservation: input.personaStateObservation });
const repoActivitySurface = identity.identityKind === "native_persona"
? projectNativePersonaBody(identity)
: projectRepoActivityObservation(readRepoActivity({ identity, storageRoot: input.config.storageRoot }));
const globalAgentDoctrine = await readGlobalAgentDoctrine({ codexHome: process.env.CODEX_HOME, userProfile: process.env.USERPROFILE });
const assembly = assemblePersonaTurn({
identity, channelId, channelPlan, recentMessages, channelSnapshots, participant: input.participant,
pendingMentions: input.pendingMentions, memorySurface: memoryContext.memorySurface,
semanticMemoryRecallSurface: memoryContext.semanticMemoryRecallSurface, repoActivitySurface,
humanPronounGuidance, bifrostDigest, githubActionsEnabled: input.config.repoFaceGithubActionsEnabled, globalAgentDoctrine,
});
return submitPersonaTurn({
jobQueue: input.storage.jobQueue, provider: input.config.repoFaceHeartbeats.provider, identityId: identity.id,
queuedAt: input.queuedAt, channelId, prompt: assembly.prompt, recentMessages,
conversationFocus: assembly.conversation.focus, conversationThreads: assembly.conversation.threads,
imageAttachments: assembly.imageAttachments,
});
}

View file

@ -0,0 +1,71 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import type { loadConfig } from "@voidbot/config";
import { faceRegistryAsRepoDiscordRegistry, loadFaceIdentityRegistry } from "@voidbot/core";
import { readBifrostGovernanceDigest } from "./bifrost-governance-source.js";
import { readGlobalAgentDoctrine } from "./global-agent-doctrine-source.js";
import { buildInspectionParticipant } from "./inspection-participant-factory.js";
import { coordinatePersonaMemoryTurn } from "./persona-memory-turn-coordinator.js";
import { readPersonaStateObservation } from "./persona-state-source.js";
import { readStoredPersonaHumanPronounGuidance } from "./persona-social-context-source.js";
import { assemblePersonaTurn } from "./persona-turn-assembler.js";
import { fetchChannelSnapshots, fetchRecentDiscordMessages } from "./turn-context-source.js";
import { buildPersonaChannelPlan } from "./turn-routing.js";
import { projectRepoActivityObservation } from "./repo-activity-projector.js";
import { readRepoActivity } from "./repo-activity-source.js";
export async function inspectPersonaTurnPrompt(input: {
config: ReturnType<typeof loadConfig>;
identityId: string;
outPath?: string;
memorySurfacePath?: string;
conversationSurfacePath?: string;
}): Promise<{ ok: true; identityId: string; promptLength: number; outPath?: string; memorySurfacePath?: string; conversationSurfacePath?: string }> {
const registry = faceRegistryAsRepoDiscordRegistry(await loadFaceIdentityRegistry(input.config.repoDiscordIdentitiesPath));
const identity = registry.identities.find((entry) => entry.id.toLowerCase() === input.identityId.toLowerCase());
if (!identity) throw new Error(`Unknown repo Face identity: ${input.identityId}`);
const channelPlan = buildPersonaChannelPlan(identity, input.config.repoFaceHeartbeats.defaultChannelId);
const channelId = channelPlan.primaryChannelId;
if (!channelId) throw new Error(`No prompt assembly channel is configured for ${identity.id}.`);
const [recentMessages, channelSnapshots, bifrostDigest] = await Promise.all([
fetchRecentDiscordMessages({ botToken: input.config.botToken, channelId, limit: 15, ignoreBotMessages: channelId === input.config.bifrostDiscordChannelId }),
fetchChannelSnapshots({ botToken: input.config.botToken, channelIds: channelPlan.snapshotChannelIds, primaryChannelId: channelId, limit: 6, bifrostDiscordChannelId: input.config.bifrostDiscordChannelId }),
input.config.repoFaceBifrostEnabled ? readBifrostGovernanceDigest({ bifrostRoot: input.config.bifrostRoot, repoName: identity.repoName, agentIdentity: identity.id }) : Promise.resolve(undefined),
]);
const roomContext = { recentMessages, channelSnapshots };
const humanPronounGuidance = await readStoredPersonaHumanPronounGuidance({ config: input.config, ...roomContext });
const stateObservation = await readPersonaStateObservation({ identity, storageRoot: input.config.storageRoot });
const memoryContext = await coordinatePersonaMemoryTurn({
identity, config: input.config, registryIdentities: registry.identities, ...roomContext,
humanPronounGuidance, stateObservation,
projectedMemoryOverride: await readOptionalSurface(input.memorySurfacePath),
});
const assembly = assemblePersonaTurn({
identity, channelId, channelPlan, channelSnapshots, recentMessages,
memorySurface: memoryContext.memorySurface,
semanticMemoryRecallSurface: memoryContext.semanticMemoryRecallSurface,
repoActivitySurface: projectRepoActivityObservation(readRepoActivity({ identity, storageRoot: input.config.storageRoot })),
conversationMemorySurface: await readOptionalSurface(input.conversationSurfacePath),
humanPronounGuidance, bifrostDigest,
participant: buildInspectionParticipant(identity, input.config.repoFaceHeartbeats.baseRecoveryMinutes),
pendingMentions: [], githubActionsEnabled: input.config.repoFaceGithubActionsEnabled,
globalAgentDoctrine: await readGlobalAgentDoctrine({ codexHome: process.env.CODEX_HOME, userProfile: process.env.USERPROFILE }),
});
if (input.outPath) {
const outPath = resolve(input.outPath);
await mkdir(dirname(outPath), { recursive: true });
await writeFile(outPath, assembly.prompt, "utf8");
}
return {
ok: true, identityId: identity.id, promptLength: assembly.prompt.length,
outPath: input.outPath ? resolve(input.outPath) : undefined,
memorySurfacePath: input.memorySurfacePath ? resolve(input.memorySurfacePath) : undefined,
conversationSurfacePath: input.conversationSurfacePath ? resolve(input.conversationSurfacePath) : undefined,
};
}
async function readOptionalSurface(path: string | undefined): Promise<string | undefined> {
if (!path) return undefined;
const content = (await readFile(resolve(path), "utf8")).trim();
return content || undefined;
}

View file

@ -0,0 +1,132 @@
import type { loadConfig } from "@voidbot/config";
import { createStateStorage, faceRegistryAsRepoDiscordRegistry, getRepoDiscordIdentityAllowedChannelIds, loadFaceIdentityRegistry } from "@voidbot/core";
import { scanActivePersonaTurns } from "./active-turn-source.js";
import { readAgentSwarmPause, readSwarmControlState } from "./control-source.js";
import { readDiscordActivitySnapshot } from "./discord-activity-source.js";
import {
advanceInitiativeClockFromWallClock, applyPendingMentionPriority, applySchedulerControls,
applySemanticPressureProjection, consumePendingMentions, finalizeSchedulerTick,
reconcileInitiativeParticipants, recordDryRunSelection, recordSchedulerSkip,
recordStaleActiveTurnRecoveries, recordTurnFailedToStart, recordTurnStarted,
rescheduleStaleOverdueParticipants, selectReadyParticipants,
} from "./initiative-engine.js";
import {
buildPersonaParticipantSpecs, dispatchPersonaParticipantTurn, pendingMentionsForPersona,
renderPersonaInitiativeAffinity,
} from "./persona-participant-dispatcher.js";
import { readPersonaStateObservations } from "./persona-state-source.js";
import { readSemanticPressure } from "./semantic-pressure-source.js";
import { readPersonaSchedulerState, writePersonaSchedulerState } from "./state-store.js";
export interface PersonaSchedulerTickResult {
ok: true;
participantCount: number;
initiativeClock: number;
queuedCount: number;
dryRun: boolean;
selected: string[];
queued: string[];
statePath: string;
skipped?: true;
reason?: "agent_swarm_paused" | "repo_face_heartbeats_disabled";
pausePath?: string;
idleCooling?: Record<string, unknown>;
}
interface PersonaSchedulerRunnerDependencies {
readPause?: typeof readAgentSwarmPause;
readState?: typeof readPersonaSchedulerState;
writeState?: typeof writePersonaSchedulerState;
}
export async function runPersonaSchedulerTick(input: {
config: ReturnType<typeof loadConfig>;
dryRun?: boolean;
force?: boolean;
now?: Date;
}, dependencies: PersonaSchedulerRunnerDependencies = {}): Promise<PersonaSchedulerTickResult> {
const { config } = input;
const dryRun = input.dryRun ?? false;
const readState = dependencies.readState ?? readPersonaSchedulerState;
const writeState = dependencies.writeState ?? writePersonaSchedulerState;
const pause = await (dependencies.readPause ?? readAgentSwarmPause)();
if (pause.paused) {
const state = await readState(config.repoFaceHeartbeats.statePath);
recordSchedulerSkip({ state, skippedAt: input.now ?? new Date(), reason: "agent_swarm_paused", details: { pausePath: pause.path, pauseReason: pause.reason } });
if (!dryRun) await writeState(config.repoFaceHeartbeats.statePath, state);
return { ok: true, participantCount: state.participants.length, initiativeClock: state.initiativeClock, queuedCount: 0, dryRun, selected: [], queued: [], skipped: true, reason: "agent_swarm_paused", pausePath: pause.path, statePath: config.repoFaceHeartbeats.statePath };
}
if (!config.repoFaceHeartbeats.enabled && !input.force) {
const state = await readState(config.repoFaceHeartbeats.statePath);
recordSchedulerSkip({ state, skippedAt: input.now ?? new Date(), reason: "repo_face_heartbeats_disabled" });
if (!dryRun) await writeState(config.repoFaceHeartbeats.statePath, state);
return { ok: true, participantCount: state.participants.length, initiativeClock: state.initiativeClock, queuedCount: 0, dryRun, selected: [], queued: [], skipped: true, reason: "repo_face_heartbeats_disabled", statePath: config.repoFaceHeartbeats.statePath };
}
const registry = faceRegistryAsRepoDiscordRegistry(await loadFaceIdentityRegistry(config.repoDiscordIdentitiesPath));
const state = await readState(config.repoFaceHeartbeats.statePath);
const now = input.now ?? new Date();
const personaStateObservations = await readPersonaStateObservations({ identities: registry.identities, storageRoot: config.storageRoot, now });
const restStates = new Map(Array.from(personaStateObservations.entries()).flatMap(([identityId, observation]) => observation.status === "ok" && "rest" in observation && observation.rest ? [[identityId, observation.rest] as const] : []));
advanceInitiativeClockFromWallClock(state, now);
const activeTurnScan = dryRun ? { active: new Map<string, string>(), staleRecovered: [] } : await scanActivePersonaTurns(config);
recordStaleActiveTurnRecoveries({ state, recoveries: activeTurnScan.staleRecovered, recoveredAt: now });
const globalHeat = (await readSwarmControlState())?.globalHeat ?? config.repoFaceHeartbeats.globalHeat;
applySchedulerControls({ state, baseRecoveryMinutes: config.repoFaceHeartbeats.baseRecoveryMinutes, globalHeat });
const completedThisTick = new Set<string>();
const participantSpecs = buildPersonaParticipantSpecs(registry.identities, config.voidModerationHeartbeatEnabled);
reconcileInitiativeParticipants({ state, specs: participantSpecs, defaultChannelId: config.repoFaceHeartbeats.defaultChannelId, speedOverrides: config.repoFaceHeartbeats.speedOverrides, heatOverrides: config.repoFaceHeartbeats.heatOverrides, baseRecoveryMinutes: config.repoFaceHeartbeats.baseRecoveryMinutes, globalHeat, activeTurns: activeTurnScan.active, completedThisTick });
rescheduleStaleOverdueParticipants(state);
applyPendingMentionPriority(state);
const idleCooling = await readDiscordActivitySnapshot({
botToken: config.botToken,
channelIds: [config.repoFaceHeartbeats.defaultChannelId, config.bifrostDiscordChannelId, ...config.indexedChannelIds, ...registry.identities.flatMap((identity) => getRepoDiscordIdentityAllowedChannelIds(identity))],
policy: config.repoFaceHeartbeats.idleCooling,
history: state.history,
now,
});
const pressure = await readSemanticPressure({
candidates: participantSpecs.flatMap((spec) => {
const participant = state.participants.find((entry) => entry.identityId === spec.id);
if (!spec.identity || spec.participantKind === "system_agent" || participant?.status !== "active" || participant.currentLoad >= 1 || completedThisTick.has(participant.identityId) || restStates.get(participant.identityId)?.isNapping === true) return [];
return [{ identityId: participant.identityId, interruptThreshold: participant.interruptThreshold, affinityText: renderPersonaInitiativeAffinity(spec), allowedChannelIds: spec.allowedChannelIds }];
}),
messages: idleCooling.observedHumanMessages,
now,
embedding: { backend: config.ragEmbeddingBackend, hashDimensions: config.ragEmbeddingDimensions, ollamaBaseUrl: config.ragOllamaBaseUrl, ollamaModel: config.ragOllamaModel, ollamaTimeoutMs: config.ragOllamaTimeoutMs },
});
applySemanticPressureProjection({ state, projections: pressure.projections, projectedAt: now, unavailableReason: pressure.unavailableReason });
const selected = selectReadyParticipants(state, config.repoFaceHeartbeats.maxJobsPerTick, completedThisTick, restStates, idleCooling);
const queued: string[] = [];
if (dryRun) {
const queuedAt = now.toISOString();
for (const participant of selected) {
const mentions = pendingMentionsForPersona(state, participant.identityId);
recordDryRunSelection(participant, state, queuedAt, mentions.length);
queued.push(participant.identityId);
}
} else if (selected.length > 0) {
const storage = await createStateStorage({ backend: config.stateStorageBackend, databaseDsn: config.databaseDsn, jobsFile: config.jobsFile, auditLogFile: config.auditLogFile, interactionMemoryFile: config.interactionMemoryFile, rateLimitStateFile: config.rateLimitStateFile });
try {
for (const participant of selected) {
const queuedAt = new Date().toISOString();
const mentions = pendingMentionsForPersona(state, participant.identityId);
const turn = await dispatchPersonaParticipantTurn({ participant, pendingMentions: mentions, registryIdentities: registry.identities, config, storage, queuedAt, personaStateObservation: personaStateObservations.get(participant.identityId) });
if (turn.created) {
queued.push(participant.identityId);
recordTurnStarted({ participant, state, queuedAt, activeJobId: turn.activeJobId, requestMessageId: turn.requestMessageId, pendingMentionCount: mentions.length });
consumePendingMentions({ state, participant, mentions, consumedAt: queuedAt, activeJobId: turn.activeJobId, requestMessageId: turn.requestMessageId });
} else if (turn.failureReason) recordTurnFailedToStart({ participant, state, queuedAt, activeJobId: turn.activeJobId, requestMessageId: turn.requestMessageId, reason: turn.failureReason });
}
} finally { await storage.close(); }
}
finalizeSchedulerTick(state, now);
if (!dryRun) await writeState(config.repoFaceHeartbeats.statePath, state);
return {
ok: true, participantCount: state.participants.length, initiativeClock: state.initiativeClock,
queuedCount: queued.length, dryRun, selected: selected.map((entry) => entry.identityId), queued,
statePath: config.repoFaceHeartbeats.statePath,
idleCooling: { ...idleCooling, observedHumanMessages: undefined, observedHumanMessageCount: idleCooling.observedHumanMessages.length },
};
}