Move Void memory maintenance into daemon

This commit is contained in:
Meta Vens 2026-07-16 04:47:17 +01:00
commit 21d12a3874
7 changed files with 261 additions and 5 deletions

View file

@ -4,6 +4,8 @@ import { loadConfig } from "@voidbot/config";
import { resolve } from "node:path";
import { runPersonaSchedulerTick } from "./persona-scheduler-runner.js";
import { runVoidPhysiologyOrgan } from "./void-physiology-organ.js";
import { runVoidMemoryMaintenance } from "./void-memory-maintenance-organ.js";
import { projectVoidMemoryOperations } from "./void-memory-text-actuator.js";
const config = loadConfig();
const intervalMs = Math.max(1, config.repoFaceHeartbeats.intervalMinutes) * 60_000;
@ -27,6 +29,16 @@ function runTick(): Promise<void> {
const physiology = await runVoidPhysiologyOrgan({ statePath: resolve(config.storageRoot, "private", "void-self-state.cc"), statusDirectory: resolve(config.storageRoot, "status") });
lastPhysiologyAt = Date.now();
console.log(`Void physiology pulse completed. ${JSON.stringify(physiology)}`);
if (physiology.memoryMaintenanceIntent) {
try {
const memory = await runVoidMemoryMaintenance({ statePath: physiology.statePath, intent: physiology.memoryMaintenanceIntent }, {
projectText: (prompt) => projectVoidMemoryOperations({ prompt, config }),
});
console.log(`Void memory-maintenance pulse completed. ${JSON.stringify(memory)}`);
} catch (error) {
console.error(`Void memory-maintenance pulse failed without automatic nap retry. ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
}
}
} catch (error) {
console.error(`Void physiology pulse failed. ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
}

View file

@ -0,0 +1,49 @@
import { applyVoidSelfStateOperation, loadVoidSelfStateTypedDocuments, type VoidSelfStateOperation, type VoidSelfStateTypedProjection } from "@voidbot/core";
import type { VoidMemoryMaintenanceIntent } from "./void-physiology-domain.js";
import { buildVoidMemoryMaintenancePrompt, parseVoidMemoryMaintenanceOperations, projectVoidMemoryMaintenanceContext } from "./void-memory-maintenance-projector.js";
export type VoidMemoryMaintenanceResult =
| { status: "skipped"; reason: "no_intent" | "already_completed_this_nap" | "already_attempted_this_nap"; runnerId?: string }
| { status: "ok"; runnerId: string; proposedOperationCount: number; appliedOperationCount: number; remainingShortTermCount: number };
export async function runVoidMemoryMaintenance(input: {
statePath: string;
intent?: VoidMemoryMaintenanceIntent;
observedAt?: Date;
}, dependencies: {
loadState?: typeof loadVoidSelfStateTypedDocuments;
applyOperation?: typeof applyVoidSelfStateOperation;
projectText: (prompt: string) => Promise<string>;
}): Promise<VoidMemoryMaintenanceResult> {
if (!input.intent) return { status: "skipped", reason: "no_intent" };
const runnerId = `void-memory-maintenance:${input.intent.napStartedAt}`;
const attemptRunnerId = `void-memory-maintenance-attempt:${input.intent.napStartedAt}`;
const loadState = dependencies.loadState ?? loadVoidSelfStateTypedDocuments;
const applyOperation = dependencies.applyOperation ?? applyVoidSelfStateOperation;
const state = await loadState({ canonicalPath: input.statePath });
if (state.scheduledRuntime.lastRuns.some((run) => run.runner === runnerId)) return { status: "skipped", reason: "already_completed_this_nap", runnerId };
if (state.scheduledRuntime.lastRuns.some((run) => run.runner === attemptRunnerId)) return { status: "skipped", reason: "already_attempted_this_nap", runnerId: attemptRunnerId };
const observedAt = input.observedAt ?? new Date();
await applyOperation({ canonicalPath: input.statePath }, {
operation: "record_scheduled_run",
run: { runner: attemptRunnerId, ranAt: observedAt.toISOString(), summary: "Started one bounded sleep memory-maintenance attempt for this nap." },
});
const context = projectVoidMemoryMaintenanceContext({ state, observedAt, forceDistillation: true });
const output = await dependencies.projectText(buildVoidMemoryMaintenancePrompt(context));
const operations = parseVoidMemoryMaintenanceOperations(output);
if (context.maintenancePressure > 0 && operations.length === 0) throw new Error(`Sleep memory maintenance returned no operations despite maintenance pressure ${context.maintenancePressure}.`);
for (const operation of operations) await applyOperation({ canonicalPath: input.statePath }, operation);
const refreshed = await loadState({ canonicalPath: input.statePath });
const remainingShortTermCount = refreshed.thoughtMemory.shortTerm.filter((memory) => !memory.retiredAt).length;
if (remainingShortTermCount > 0) throw new Error(`Sleep memory maintenance left ${remainingShortTermCount} short-term memories unpromoted.`);
const receipt: VoidSelfStateOperation = {
operation: "record_scheduled_run",
run: { runner: runnerId, ranAt: observedAt.toISOString(), summary: `Applied ${operations.length} typed memory-maintenance operation${operations.length === 1 ? "" : "s"}; no short-term residue remained.` },
};
await applyOperation({ canonicalPath: input.statePath }, receipt);
return { status: "ok", runnerId, proposedOperationCount: operations.length, appliedOperationCount: operations.length, remainingShortTermCount };
}
export function hasVoidMemoryMaintenanceCompleted(state: VoidSelfStateTypedProjection, intent: VoidMemoryMaintenanceIntent): boolean {
return state.scheduledRuntime.lastRuns.some((run) => run.runner === `void-memory-maintenance:${intent.napStartedAt}`);
}

View file

@ -0,0 +1,103 @@
import { voidSelfStateOperationSchema, type VoidSelfStateOperation, type VoidSelfStateTypedProjection } from "@voidbot/core";
const ALLOWED_OPERATIONS = new Set([
"merge_incubation_support", "queue_candidate_intervention", "retire_candidate_intervention",
"upsert_agency_pressure", "retire_agency_pressure", "upsert_affect_need", "retire_affect_need",
"upsert_social_bond", "retire_social_bond", "upsert_status_read", "retire_status_read",
"update_mood_dimensions", "propose_memory_distillation", "apply_memory_distillation",
"revise_durable_memory", "retire_durable_memory", "crystallize_memory_into_identity",
"prune_short_term_memories",
]);
export interface VoidMemoryMaintenanceContext {
mode: "sleep_maintenance" | "awake_memory_maintenance";
operationTimestamp: string;
maintenancePressure: number;
forceDistillation: boolean;
shortTermMemoryCount: number;
longTermMemoryCount: number;
incubationCount: number;
activeAgencyPressureCount: number;
activeCandidateCount: number;
shortTermMemories: unknown[];
memories: unknown[];
incubation: unknown[];
agencyPressure: unknown[];
candidateInterventions: unknown[];
scheduledRuntime: unknown;
speechReceipts: unknown[];
}
export function projectVoidMemoryMaintenanceContext(input: {
state: VoidSelfStateTypedProjection;
observedAt: Date;
forceDistillation?: boolean;
}): VoidMemoryMaintenanceContext {
const state = input.state;
const sleeping = input.forceDistillation === true || state.scheduledRuntime.sleepCycle.isNapping;
const activeShortTerm = state.thoughtMemory.shortTerm.filter((entry) => !entry.retiredAt);
const activeAgency = state.agencyPressure.pressures.filter((entry) => ["active", "cooling", "ready_to_act"].includes(entry.status));
const activeCandidates = state.candidateInterventions.interventions.filter((entry) => entry.status === "queued" || entry.status === "deferred");
const maintenancePressure = activeShortTerm.length + state.thoughtMemory.incubation.length + activeAgency.length + activeCandidates.length;
const relative = <T>(value: T): T => projectRelativeChronology(value, input.observedAt) as T;
return {
mode: sleeping ? "sleep_maintenance" : "awake_memory_maintenance",
operationTimestamp: input.observedAt.toISOString(),
maintenancePressure,
forceDistillation: sleeping && maintenancePressure > 0,
shortTermMemoryCount: activeShortTerm.length,
longTermMemoryCount: state.thoughtMemory.memories.length,
incubationCount: state.thoughtMemory.incubation.length,
activeAgencyPressureCount: activeAgency.length,
activeCandidateCount: activeCandidates.length,
shortTermMemories: relative(activeShortTerm), memories: relative(state.thoughtMemory.memories),
incubation: relative(state.thoughtMemory.incubation), agencyPressure: relative(activeAgency),
candidateInterventions: relative(activeCandidates), scheduledRuntime: relative(state.scheduledRuntime),
speechReceipts: relative(state.speechReceipts.recentReceipts),
};
}
export function buildVoidMemoryMaintenancePrompt(context: VoidMemoryMaintenanceContext): string {
return [
"You are Void's private memory-maintenance organ. This is not moderation or public speech.",
"Return only a JSON array of complete typed Void self-state operation objects. Do not use markdown fences, commentary, tools, or file writes.",
`Allowed operations: ${[...ALLOWED_OPERATIONS].join(", ")}.`,
"Never emit cursor, receipt, sleep-cycle, or speaking-pressure operations. Omit absent optional fields; never emit null.",
"Every durable memory move must preserve a concrete target, claim or question, tension, future-action implication, and anchors or tag anchor:missing.",
"During sleep every short-term memory must be consumed by apply_memory_distillation, or merged into incubation and pruned, or honestly pruned.",
"Use operationTimestamp for required operation timestamps. Context chronology is relative evidence, not schema-ready timestamp text.",
context.forceDistillation ? "Sleep pressure is active. Returning [] is invalid." : "If no meaning-preserving move exists, return [].",
"Maintenance context:",
JSON.stringify(context, null, 2),
].join("\n\n");
}
export function parseVoidMemoryMaintenanceOperations(outputText: string): VoidSelfStateOperation[] {
const trimmed = outputText.trim();
const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)?.[1]?.trim();
const candidate = fenced ?? trimmed;
let raw: unknown;
try { raw = JSON.parse(candidate); } catch (error) { throw new Error(`Memory maintenance output is not valid JSON: ${error instanceof Error ? error.message : String(error)}`); }
if (!Array.isArray(raw)) throw new Error("Memory maintenance output must be a JSON array.");
return raw.map((entry, index) => {
const operation = voidSelfStateOperationSchema.parse(entry);
if (!ALLOWED_OPERATIONS.has(operation.operation)) throw new Error(`Memory maintenance operation ${index + 1} is not allowed: ${operation.operation}.`);
return operation;
});
}
function projectRelativeChronology(value: unknown, observedAt: Date, key = ""): unknown {
if (Array.isArray(value)) return value.map((entry) => projectRelativeChronology(entry, observedAt));
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([entryKey, entry]) => [entryKey, projectRelativeChronology(entry, observedAt, entryKey)]));
if (typeof value === "string" && /(?:At|Timestamp)$/.test(key) && Number.isFinite(Date.parse(value))) return relativeTime(value, observedAt);
return value;
}
function relativeTime(value: string, observedAt: Date): string {
const differenceMs = observedAt.getTime() - Date.parse(value);
if (!Number.isFinite(differenceMs)) return "unknown time";
const future = differenceMs < 0;
const minutes = Math.max(0, Math.round(Math.abs(differenceMs) / 60_000));
const amount = minutes < 60 ? `${minutes} minute${minutes === 1 ? "" : "s"}` : minutes < 1_440 ? `${Math.round(minutes / 60)} hour${Math.round(minutes / 60) === 1 ? "" : "s"}` : `${Math.round(minutes / 1_440)} day${Math.round(minutes / 1_440) === 1 ? "" : "s"}`;
return future ? `in ${amount}` : `${amount} ago`;
}

View file

@ -0,0 +1,33 @@
import { readFile } from "node:fs/promises";
import type { loadConfig } from "@voidbot/config";
export async function projectVoidMemoryOperations(input: {
prompt: string;
config: ReturnType<typeof loadConfig>;
model?: string;
}, dependencies: { fetch?: typeof fetch; readText?: (path: string) => Promise<string> } = {}): Promise<string> {
const api = input.config.openAiApi;
const apiKey = api.apiKey ?? (api.apiKeyFile ? (await (dependencies.readText ?? ((path) => readFile(path, "utf8")))(api.apiKeyFile)).trim() : undefined);
if (!apiKey) throw new Error("Void memory maintenance requires the configured OpenAI-compatible API key.");
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), api.timeoutMs);
try {
const response = await (dependencies.fetch ?? fetch)(`${api.baseUrl.replace(/\/+$/, "")}/chat/completions`, {
method: "POST",
headers: { "content-type": "application/json", [api.authHeader]: api.authHeader.toLowerCase() === "authorization" ? `Bearer ${apiKey}` : apiKey },
body: JSON.stringify({ model: input.model ?? process.env.VOID_MEMORY_MAINTENANCE_MODEL ?? api.model, messages: [{ role: "user", content: input.prompt }], stream: false, max_completion_tokens: Math.min(api.maxCompletionTokens, Math.max(256, Number(process.env.VOID_MEMORY_MAINTENANCE_MAX_COMPLETION_TOKENS) || 2048)) }),
signal: controller.signal,
});
const responseText = await response.text();
if (!response.ok) throw new Error(`Void memory model request failed with ${response.status}: ${redact(responseText, apiKey).slice(0, 1000)}`);
const payload = JSON.parse(responseText) as { choices?: Array<{ message?: { content?: unknown } }> };
const content = payload.choices?.[0]?.message?.content;
if (typeof content !== "string" || !content.trim()) throw new Error("Void memory model response contained no assistant text.");
return content.trim();
} catch (error) {
if (error instanceof Error && error.name === "AbortError") throw new Error(`Void memory model request timed out after ${api.timeoutMs}ms.`);
throw error;
} finally { clearTimeout(timeout); }
}
function redact(value: string, secret: string): string { return secret ? value.split(secret).join("[redacted]") : value; }

View file

@ -444,6 +444,12 @@ export const voidThoughtMemorySchema = z.object({
updatedAt: timestampSchema,
}).strict();
const scheduledRunSchema = z.object({
runner: nonEmptyStringSchema,
ranAt: timestampSchema,
summary: z.string().trim().min(1).max(1000),
}).strict();
export const voidScheduledRuntimeSchema = z.object({
schemaVersion: z.literal(1),
sleepCycle: z.object({
@ -461,11 +467,7 @@ export const voidScheduledRuntimeSchema = z.object({
lastSpokeAt: timestampSchema.optional(),
lastHeraldAt: timestampSchema.optional(),
}).strict(),
lastRuns: z.array(z.object({
runner: nonEmptyStringSchema,
ranAt: timestampSchema,
summary: z.string().trim().min(1).max(1000),
}).strict()).default([]),
lastRuns: z.array(scheduledRunSchema).default([]),
updatedAt: timestampSchema,
}).strict();
@ -735,6 +737,10 @@ export const voidSelfStateOperationSchema = z.discriminatedUnion("operation", [
operation: z.literal("update_speaking_pressure"),
speakingPressure: voidScheduledRuntimeSchema.shape.speakingPressure,
}).strict(),
z.object({
operation: z.literal("record_scheduled_run"),
run: scheduledRunSchema,
}).strict(),
z.object({
operation: z.literal("propose_memory_distillation"),
proposalId: nonEmptyStringSchema,

View file

@ -467,6 +467,13 @@ function applyTypedOperation(
state.scheduledRuntime.speakingPressure = operation.speakingPressure;
state.scheduledRuntime.updatedAt = new Date().toISOString();
return;
case "record_scheduled_run":
state.scheduledRuntime.lastRuns = [
...state.scheduledRuntime.lastRuns.filter((entry) => entry.runner !== operation.run.runner),
operation.run,
].slice(-64);
state.scheduledRuntime.updatedAt = operation.run.ranAt;
return;
case "propose_memory_distillation":
return;
case "apply_memory_distillation":

View file

@ -81,6 +81,9 @@ import { buildInspectionParticipant } from "../apps/persona-scheduler/dist/inspe
import { runPersonaSchedulerTick } from "../apps/persona-scheduler/dist/persona-scheduler-runner.js";
import { projectVoidPhysiology } from "../apps/persona-scheduler/dist/void-physiology-domain.js";
import { runVoidPhysiologyOrgan } from "../apps/persona-scheduler/dist/void-physiology-organ.js";
import { buildVoidMemoryMaintenancePrompt, parseVoidMemoryMaintenanceOperations, projectVoidMemoryMaintenanceContext } from "../apps/persona-scheduler/dist/void-memory-maintenance-projector.js";
import { runVoidMemoryMaintenance } from "../apps/persona-scheduler/dist/void-memory-maintenance-organ.js";
import { projectVoidMemoryOperations } from "../apps/persona-scheduler/dist/void-memory-text-actuator.js";
import { projectGamecultPersonaState } from "../apps/persona-scheduler/dist/persona-standard-state-projector.js";
import { projectPersonaStatePacket } from "../apps/persona-scheduler/dist/persona-state-packet-projector.js";
import { extractLastPersonaProjectionMessage, isRetryablePersonaProjectionFailure } from "../apps/persona-scheduler/dist/persona-text-projection-actuator.js";
@ -816,6 +819,49 @@ const physiologyOrgan = await runVoidPhysiologyOrgan({ statePath: "void-self-sta
});
assert.deepEqual(appliedPhysiologyOperations, ["update_sleep_cycle", "update_speaking_pressure"], "the daemon physiology organ applies only domain-projected typed operations through the state-service port");
assert.equal(physiologyOrgan.memoryMaintenanceIntent?.reason, "sleep_short_term_pressure", "the daemon organ exposes maintenance intent for a separate memory owner");
const memoryMaintenanceContext = projectVoidMemoryMaintenanceContext({ state: physiologyState, observedAt: physiologyObservedAt, forceDistillation: true });
assert.equal(memoryMaintenanceContext.forceDistillation, true, "sleep memory context exposes explicit maintenance pressure without deciding the memory operation");
assert.match(JSON.stringify(memoryMaintenanceContext.shortTermMemories), /ago|short-term/, "prompt-facing memory context projects chronology instead of dumping exact state timestamps");
assert.doesNotMatch(buildVoidMemoryMaintenancePrompt(memoryMaintenanceContext), /OPERATION_OUTPUT_PATH|apply-operation/, "portable maintenance prompts return operations directly and cannot preserve the filesystem tool-writing contract");
const parsedMaintenance = parseVoidMemoryMaintenanceOperations(JSON.stringify([{
operation: "prune_short_term_memories",
sourceMemoryIds: ["short-term"],
prunedAt: physiologyObservedAt.toISOString(),
reason: "The fixture residue has no durable claim beyond proving the typed boundary.",
}]));
assert.equal(parsedMaintenance[0]?.operation, "prune_short_term_memories", "memory output parsing crosses the canonical operation schema before application");
assert.throws(() => parseVoidMemoryMaintenanceOperations(JSON.stringify([{ operation: "update_sleep_cycle", sleepCycle: physiology.sleepCycle }])), /not allowed/, "memory maintenance cannot annex physiology operations even when they are schema-valid");
const maintainedState = structuredClone(physiologyState);
let memoryModelCalls = 0;
const memoryMaintenanceDependencies = {
loadState: async () => maintainedState,
projectText: async () => {
memoryModelCalls += 1;
return JSON.stringify([{ operation: "prune_short_term_memories", sourceMemoryIds: ["short-term"], prunedAt: physiologyObservedAt.toISOString(), reason: "The fixture residue has no durable meaning beyond proving nap-level ownership." }]);
},
applyOperation: async (_store: unknown, operation: { operation: string; run?: { runner: string; ranAt: string; summary: string } }) => {
if (operation.operation === "prune_short_term_memories") maintainedState.thoughtMemory.shortTerm = [];
if (operation.operation === "record_scheduled_run" && operation.run) maintainedState.scheduledRuntime.lastRuns.push(operation.run);
return maintainedState;
},
};
const maintenanceIntent = physiology.memoryMaintenanceIntent;
assert.ok(maintenanceIntent, "physiology fixture supplies memory-maintenance intent");
const maintained = await runVoidMemoryMaintenance({ statePath: "void-self-state.cc", intent: maintenanceIntent, observedAt: physiologyObservedAt }, memoryMaintenanceDependencies as never);
assert.equal(maintained.status, "ok", "the memory organ validates, applies, verifies, and receipts one sleep pass");
const duplicateMaintenance = await runVoidMemoryMaintenance({ statePath: "void-self-state.cc", intent: maintenanceIntent, observedAt: physiologyObservedAt }, memoryMaintenanceDependencies as never);
assert.deepEqual(duplicateMaintenance, { status: "skipped", reason: "already_completed_this_nap", runnerId: `void-memory-maintenance:${maintenanceIntent.napStartedAt}` }, "the typed scheduled-run receipt makes repeated intent idempotent for one nap");
assert.equal(memoryModelCalls, 1, "one nap can authorize at most one memory model pass");
let memoryRequestBody: Record<string, unknown> | undefined;
const memoryModelOutput = await projectVoidMemoryOperations({ prompt: "Maintain memory.", config: { openAiApi: { baseUrl: "https://model.invalid/v1", apiKey: "secret", model: "memory-model", timeoutMs: 1000, authHeader: "Authorization", maxCompletionTokens: 512 } } as never }, {
fetch: async (_url, init) => {
memoryRequestBody = JSON.parse(String(init?.body));
return new Response(JSON.stringify({ choices: [{ message: { content: "[]" } }] }), { status: 200 });
},
});
assert.equal(memoryModelOutput, "[]", "the portable memory actuator returns only model text to the operation parser");
assert.equal(memoryRequestBody?.model, "memory-model", "the memory actuator uses one explicit configured model and bounded completion budget");
assert.equal(memoryRequestBody?.tools, undefined, "memory maintenance cannot acquire filesystem or side-effect tools through the model actuator");
const moderationLaunchCommand = buildVoidModerationLaunchCommand({
pendingMentionsPath: "C:/Void's state/pending.json",
runnerScript: "C:/VoidBot/scripts/run.ps1",