Rebuild self-state runners on typed store

This commit is contained in:
Meta Vens 2026-05-16 18:43:53 +01:00
commit a10e7e9171
12 changed files with 448 additions and 2518 deletions

View file

@ -4,14 +4,12 @@ import {
type VoidSelfStateContext,
} from "@voidbot/shared";
import { loadModerationState, type ModerationState } from "./moderation-state-store";
import {
projectModerationStateToTypedSelfState,
type VoidSelfStateTypedProjection,
} from "./void-self-state-projection";
type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
type JsonObject = { [key: string]: JsonValue };
type VoidScheduledRuntime,
type VoidThoughtMemory,
} from "./void-self-state-domain";
import { type VoidSelfStateTypedProjection } from "./void-self-state-projection";
import { loadVoidSelfStateTypedDocuments } from "./void-self-state-service";
export interface LoadVoidSelfStateOptions {
recentMessages?: SourceMessage[];
@ -22,10 +20,9 @@ export async function loadVoidSelfState(
statePath: string,
options: LoadVoidSelfStateOptions = {},
): Promise<VoidSelfStateContext | undefined> {
let parsed: ModerationState;
let typedProjection: VoidSelfStateTypedProjection;
try {
parsed = await loadModerationState(statePath);
typedProjection = await loadVoidSelfStateTypedDocuments({ canonicalPath: statePath });
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
@ -36,170 +33,131 @@ export async function loadVoidSelfState(
throw error;
}
const legacyProjection = parsed as unknown as JsonObject;
const typedProjection = projectModerationStateToTypedSelfState(parsed);
const projection = buildVoidSelfStateProjection(typedProjection);
return {
sourcePath: statePath,
loadedAt: new Date().toISOString(),
summary: renderVoidSelfStateSummary(legacyProjection, options),
summary: renderTypedVoidSelfStateSummary(typedProjection, options),
projection,
};
}
function renderVoidSelfStateSummary(
state: JsonObject,
function renderTypedVoidSelfStateSummary(
state: VoidSelfStateTypedProjection,
options: LoadVoidSelfStateOptions,
): string {
const identity = getObject(state, "identity");
const goals = getArray(state, "goals");
const memories = getObject(state, "memories");
const runtime = getObject(state, "moderation_runtime");
const canonicalState = getObject(state, "canonical_state");
const thoughtLanes = getObject(runtime, "thought_lanes");
const bridge = getObject(runtime, "bridge");
const memoryResonance = getObject(runtime, "memory_resonance");
const incubation = getObject(runtime, "incubation");
const privateNotes = getStringArray(identity, "private_notes").slice(0, 4);
const activeGoals = goals
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.filter((goal) => readString(goal, "status") === "active")
const profile = state.selfProfile;
const topValues = state.selfProfile.values
.sort((left, right) => right.priority - left.priority)
.slice(0, 4)
.map((goal) => readString(goal, "label"))
.filter((value): value is string => Boolean(value));
const topValues = getArray(canonicalState, "values")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.sort(
(left, right) =>
(readNumber(right, "priority") ?? 0) - (readNumber(left, "priority") ?? 0),
)
.slice(0, 4)
.map((value) => readString(value, "label"))
.filter((value): value is string => Boolean(value));
const voiceSummary = summarizeCurrentActivations(getObject(canonicalState, "voice_style"), 5);
const behavioralSummary = summarizeCurrentActivations(
getObject(canonicalState, "behavioral_dimensions"),
5,
);
const semanticMemories = getArray(memories, "semantic")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.map((value) => value.label);
const memories = state.thoughtMemory.memories
.slice(-6)
.map((memory) => {
const subject = readString(memory, "subjectLabel") ?? readString(memory, "subjectId") ?? "unknown";
const summary = readString(memory, "summary") ?? "(no summary)";
const kind = readString(memory, "kind");
const suffix =
kind === "identity_seam"
? " [identity seam]"
: kind === "distilled_seam"
? " [distilled seam]"
: "";
return `- ${subject}${suffix}: ${summary}`;
});
const analyticThreads = summarizeThoughtLane(getObject(thoughtLanes, "analytic"), 3);
const associativeThreads = summarizeThoughtLane(getObject(thoughtLanes, "associative"), 3);
const bridgeSyntheses = summarizeBridgeSyntheses(bridge, 3);
const topicSaturation = summarizeTopicSaturation(bridge, 3);
const refractoryTopics = summarizeRefractoryTopics(bridge, 3);
const sourceCoverage = summarizeSourceCoverage(bridge);
const unresolvedTensions = summarizeUnresolvedTensions(bridge, 3);
const resonanceClusters = summarizeResonanceClusters(memoryResonance, 3);
const incubatingThoughts = summarizeIncubatingThoughts(incubation, 3);
const openCases = summarizeOpenCases(runtime, 3);
const discomforts = summarizeDiscomforts(runtime, 3);
const activeTensions = summarizeActiveTensions(runtime, 3);
const selfAdvocacy = summarizeAdvocacyRequests(runtime, "self_advocacy_requests", 2);
const worldAdvocacy = summarizeAdvocacyRequests(runtime, "world_advocacy_requests", 2);
const candidateInterventions = getArray(runtime, "candidate_interventions")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.reverse()
.map((memory) => renderTypedMemory(memory));
const incubation = state.thoughtMemory.incubation
.filter((thread) => thread.status !== "retired")
.sort((left, right) => right.maturation - left.maturation)
.slice(0, 4)
.map((thread) => renderTypedIncubationThread(thread));
const openCases = state.moderationCursor.openCases
.filter((entry) => !["answered", "resolved", "closed", "retired", "dropped"].includes(entry.status))
.slice(-4)
.reverse()
.map((entry) => `- ${entry.summary}${entry.authorName ? ` [from ${entry.authorName}]` : ""}`);
const interventions = state.candidateInterventions.interventions
.filter((entry) => entry.status === "queued" || entry.status === "deferred")
.slice(-3)
.map((intervention) => {
const summary = readString(intervention, "summary") ?? "draft intervention";
const draft = readString(intervention, "draft") ?? "(no draft)";
return `- ${summary}: ${draft}`;
});
const speakingBias = getObject(runtime, "speaking_bias");
const lastRun = getObject(runtime, "last_run");
const lastRunSummary = readString(lastRun, "summary");
const sleepCycleSummary = renderSleepCycleSummary(runtime, memories);
const transientRoomLog = renderTransientRoomLog(options);
.reverse()
.map((entry) => `- ${entry.summary}: ${entry.draft}`);
return [
`- Identity: ${readString(identity, "name") ?? "Void"}${readString(identity, "public_description") ? ` - ${readString(identity, "public_description")}` : ""}`,
privateNotes.length > 0
? `- Private notes: ${privateNotes.join(" | ")}`
`- Identity: ${profile.publicName}${profile.publicDescription ? ` - ${profile.publicDescription}` : ""}`,
profile.privateNotes.length > 0
? `- Private notes: ${profile.privateNotes.slice(0, 4).join(" | ")}`
: "- Private notes: none recorded.",
activeGoals.length > 0
? `- Active goals: ${activeGoals.join(" | ")}`
: "- Active goals: none recorded.",
topValues.length > 0
? `- Highest-priority values: ${topValues.join(" | ")}`
: "- Highest-priority values: none recorded.",
voiceSummary
? `- Current voice activations: ${voiceSummary}`
: "- Current voice activations: none highlighted.",
behavioralSummary
? `- Current behavioral activations: ${behavioralSummary}`
: "- Current behavioral activations: none highlighted.",
sleepCycleSummary,
lastRunSummary ? `- Last moderation run: ${lastRunSummary}` : "- Last moderation run: none recorded.",
renderTypedSleepCycleSummary(state.scheduledRuntime, state.thoughtMemory),
renderTypedSpeakingPressureSummary(state.scheduledRuntime),
openCases.length > 0
? ["- Outstanding room obligations:", ...openCases].join("\n")
: "- Outstanding room obligations: none recorded.",
semanticMemories.length > 0
? ["- Distilled seam memory:", ...semanticMemories].join("\n")
: "- Distilled seam memory: none recorded.",
analyticThreads.length > 0
? ["- Analytic active threads:", ...analyticThreads].join("\n")
: "- Analytic active threads: none recorded.",
associativeThreads.length > 0
? ["- Associative active threads:", ...associativeThreads].join("\n")
: "- Associative active threads: none recorded.",
bridgeSyntheses.length > 0
? ["- Bridge syntheses:", ...bridgeSyntheses].join("\n")
: "- Bridge syntheses: none recorded.",
resonanceClusters.length > 0
? ["- Resonance clusters:", ...resonanceClusters].join("\n")
: "- Resonance clusters: none recorded.",
incubatingThoughts.length > 0
? ["- Incubating thoughts:", ...incubatingThoughts].join("\n")
: "- Incubating thoughts: none recorded.",
topicSaturation.length > 0
? ["- Topic saturation warnings:", ...topicSaturation].join("\n")
: "- Topic saturation warnings: none recorded.",
refractoryTopics.length > 0
? ["- Refractory topics:", ...refractoryTopics].join("\n")
: "- Refractory topics: none recorded.",
sourceCoverage ? `- Source coverage pressure: ${sourceCoverage}` : "- Source coverage pressure: none recorded.",
unresolvedTensions.length > 0
? ["- Unresolved tensions:", ...unresolvedTensions].join("\n")
: "- Unresolved tensions: none recorded.",
discomforts.length > 0
? ["- Current discomforts:", ...discomforts].join("\n")
: "- Current discomforts: none recorded.",
activeTensions.length > 0
? ["- Active value-backed tensions:", ...activeTensions].join("\n")
: "- Active value-backed tensions: none recorded.",
selfAdvocacy.length > 0
? ["- Self-advocacy requests:", ...selfAdvocacy].join("\n")
: "- Self-advocacy requests: none recorded.",
worldAdvocacy.length > 0
? ["- World-advocacy requests:", ...worldAdvocacy].join("\n")
: "- World-advocacy requests: none recorded.",
renderSpeakingBiasSummary(speakingBias),
candidateInterventions.length > 0
? ["- Draft conversation/intervention seeds:", ...candidateInterventions].join("\n")
: "- Draft conversation/intervention seeds: none recorded.",
transientRoomLog,
memories.length > 0
? ["- Typed memory:", ...memories].join("\n")
: "- Typed memory: none recorded.",
incubation.length > 0
? ["- Incubating threads:", ...incubation].join("\n")
: "- Incubating threads: none recorded.",
interventions.length > 0
? ["- Candidate interventions:", ...interventions].join("\n")
: "- Candidate interventions: none recorded.",
renderTransientRoomLog(options),
].join("\n");
}
function renderTypedMemory(memory: VoidThoughtMemory["memories"][number]): string {
const target = memory.target.label ?? memory.target.id;
const meaning = [
memory.claim ? `claim=${memory.claim}` : undefined,
memory.question ? `question=${memory.question}` : undefined,
memory.tension ? `tension=${memory.tension}` : undefined,
memory.actionImplication ? `next=${memory.actionImplication}` : undefined,
].filter((value): value is string => Boolean(value));
return `- ${target} [${memory.kind}]: ${memory.summary}${meaning.length > 0 ? ` (${meaning.join("; ")})` : ""}`;
}
function renderTypedIncubationThread(thread: VoidThoughtMemory["incubation"][number]): string {
const target = thread.target.label ?? thread.target.id;
const metrics = [
`status=${thread.status}`,
`maturation=${thread.maturation.toFixed(2)}`,
thread.desireToSpeak !== undefined ? `speak=${thread.desireToSpeak.toFixed(2)}` : undefined,
thread.noveltyToSelf !== undefined ? `self=${thread.noveltyToSelf.toFixed(2)}` : undefined,
thread.noveltyToRoom !== undefined ? `room=${thread.noveltyToRoom.toFixed(2)}` : undefined,
].filter((value): value is string => Boolean(value));
return `- ${thread.topic} -> ${target} [${metrics.join("; ")}]: ${thread.summary}`;
}
function renderTypedSleepCycleSummary(
runtime: VoidScheduledRuntime,
thoughtMemory: VoidThoughtMemory,
): string {
const sleepCycle = runtime.sleepCycle;
const dreams = thoughtMemory.memories
.filter((memory) => memory.kind === "dream_residue")
.slice(-2)
.reverse()
.map((memory) => `${memory.target.label ?? memory.target.id}: ${memory.summary}`);
const headline = sleepCycle.isNapping
? `- Sleep cycle: napping${sleepCycle.currentNapEndsAt ? ` until ${sleepCycle.currentNapEndsAt}` : ""}.`
: `- Sleep cycle: awake${sleepCycle.nextNapStartsAt ? `; next nap ${sleepCycle.nextNapStartsAt}` : ""}.`;
const themeLine =
sleepCycle.activeDreamThemes.length > 0
? `- Active dream themes: ${sleepCycle.activeDreamThemes.join(" | ")}`
: "- Active dream themes: none recorded.";
const dreamLine =
dreams.length > 0
? `- Recent dream residue: ${dreams.join(" | ")}`
: "- Recent dream residue: none recorded.";
return [headline, themeLine, dreamLine].join("\n");
}
function renderTypedSpeakingPressureSummary(runtime: VoidScheduledRuntime): string {
const pressure = runtime.speakingPressure;
const parts = [
`needToSpeak=${pressure.needToSpeak.toFixed(2)}`,
pressure.confessionPressure !== undefined ? `confession=${pressure.confessionPressure.toFixed(2)}` : undefined,
pressure.noveltyPressure !== undefined ? `novelty=${pressure.noveltyPressure.toFixed(2)}` : undefined,
pressure.recentSpeechDamping !== undefined ? `speechDamping=${pressure.recentSpeechDamping.toFixed(2)}` : undefined,
].filter((value): value is string => Boolean(value));
return `- Speaking pressure: ${parts.join(", ")}`;
}
function renderTransientRoomLog(options: LoadVoidSelfStateOptions): string {
const recentMessages = (options.recentMessages ?? []).slice(-10);
const guildName = options.guildContext?.guildName ?? options.guildContext?.guildId ?? "(direct/unknown)";
@ -226,368 +184,6 @@ function renderTransientRoomLog(options: LoadVoidSelfStateOptions): string {
].join("\n");
}
function summarizeOpenCases(runtime: JsonObject | undefined, limit: number): string[] {
const terminalStatuses = new Set(["answered", "resolved", "closed", "retired", "dropped"]);
return getArray(runtime, "open_cases")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.filter((openCase) => {
const status = readString(openCase, "status");
return !status || !terminalStatuses.has(status);
})
.slice(-limit)
.reverse()
.map((openCase) => {
const summary =
readString(openCase, "summary") ??
readString(openCase, "question") ??
"unlabeled room obligation";
const authorName = readString(openCase, "authorName");
const status = readString(openCase, "status");
const whyItMatters = readString(openCase, "whyItMatters");
const tags = [status, authorName ? `from ${authorName}` : undefined].filter(
(value): value is string => Boolean(value),
);
return `- ${summary}${tags.length > 0 ? ` [${tags.join("; ")}]` : ""}${whyItMatters ? ` - ${whyItMatters}` : ""}`;
});
}
function summarizeDiscomforts(runtime: JsonObject | undefined, limit: number): string[] {
return getArray(runtime, "discomforts")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.sort(
(left, right) =>
(readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0),
)
.slice(0, limit)
.map((entry) => {
const summary = readString(entry, "summary") ?? "unlabeled discomfort";
const targetKind = readString(entry, "targetKind");
const domain = readString(entry, "domain");
const intensity = readNumber(entry, "intensity");
const persistence = readNumber(entry, "persistence");
const metrics = [
domain,
targetKind,
intensity !== undefined ? `intensity=${intensity.toFixed(2)}` : undefined,
persistence !== undefined ? `persistence=${persistence}` : undefined,
].filter((value): value is string => Boolean(value));
return `- ${summary}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}`;
});
}
function summarizeActiveTensions(runtime: JsonObject | undefined, limit: number): string[] {
return getArray(runtime, "active_tensions")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.sort(
(left, right) =>
(readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0),
)
.slice(0, limit)
.map((entry) => {
const topic = readString(entry, "topic") ?? "untitled tension";
const opinion = readString(entry, "opinion") ?? readString(entry, "summary") ?? "(no opinion)";
const domain = readString(entry, "domain");
const intensity = readNumber(entry, "intensity");
const persistence = readNumber(entry, "persistence");
const metrics = [
domain,
intensity !== undefined ? `intensity=${intensity.toFixed(2)}` : undefined,
persistence !== undefined ? `persistence=${persistence}` : undefined,
].filter((value): value is string => Boolean(value));
return `- ${topic}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}: ${opinion}`;
});
}
function summarizeAdvocacyRequests(
runtime: JsonObject | undefined,
key: string,
limit: number,
): string[] {
return getArray(runtime, key)
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.sort(
(left, right) =>
(readNumber(right, "intensity") ?? 0) - (readNumber(left, "intensity") ?? 0),
)
.slice(0, limit)
.map((entry) => {
const summary = readString(entry, "summary") ?? "advocacy request";
const request = readString(entry, "request") ?? "(no request)";
const status = readString(entry, "status");
const intensity = readNumber(entry, "intensity");
const persistence = readNumber(entry, "persistence");
const metrics = [
status,
intensity !== undefined ? `intensity=${intensity.toFixed(2)}` : undefined,
persistence !== undefined ? `persistence=${persistence}` : undefined,
].filter((value): value is string => Boolean(value));
return `- ${summary}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}: ${request}`;
});
}
function summarizeThoughtLane(lane: JsonObject | undefined, limit: number): string[] {
return getArray(lane, "active_threads")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.slice(0, limit)
.map((thread) => {
const topic = readString(thread, "topic") ?? "untitled";
const claim = readString(thread, "claim") ?? "(no claim)";
const roomRelevance = readNumber(thread, "roomRelevance");
const novelty = readNumber(thread, "novelty");
const desireToSpeak = readNumber(thread, "desireToSpeak");
const counterweight = readString(thread, "counterweight");
const metrics = [
roomRelevance !== undefined ? `room=${roomRelevance.toFixed(2)}` : undefined,
novelty !== undefined ? `novelty=${novelty.toFixed(2)}` : undefined,
desireToSpeak !== undefined ? `speak=${desireToSpeak.toFixed(2)}` : undefined,
].filter((value): value is string => Boolean(value));
const counterweightText = counterweight ? ` Counterweight: ${counterweight}` : "";
return `- ${topic}: ${claim}${metrics.length > 0 ? ` (${metrics.join(", ")})` : ""}${counterweightText}`;
});
}
function summarizeBridgeSyntheses(bridge: JsonObject | undefined, limit: number): string[] {
return getArray(bridge, "recent_syntheses")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.slice(-limit)
.reverse()
.map((synthesis) => {
const summary = readString(synthesis, "summary") ?? "(no summary)";
const laneBalance = readString(synthesis, "laneBalance");
const speakDecision = readString(synthesis, "speakDecision");
const tags = [laneBalance, speakDecision].filter((value): value is string => Boolean(value));
return `- ${summary}${tags.length > 0 ? ` [${tags.join("; ")}]` : ""}`;
});
}
function summarizeResonanceClusters(memoryResonance: JsonObject | undefined, limit: number): string[] {
return getArray(memoryResonance, "clusters")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.sort(
(left, right) =>
(readNumber(right, "resonance") ?? 0) - (readNumber(left, "resonance") ?? 0),
)
.slice(0, limit)
.map((cluster) => {
const label = readString(cluster, "label") ?? "untitled";
const summary = readString(cluster, "summary") ?? "(no summary)";
const resonance = readNumber(cluster, "resonance");
const focusKind = readString(cluster, "focusKind");
const targetKind = readString(cluster, "targetKind");
const concreteness = readNumber(getObject(cluster, "curiosityProfile"), "concreteness");
const metrics = [
focusKind,
targetKind,
concreteness !== undefined ? `concrete=${concreteness.toFixed(2)}` : undefined,
resonance !== undefined ? `resonance=${resonance.toFixed(2)}` : undefined,
].filter((value): value is string => Boolean(value));
return `- ${label}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}: ${summary}`;
});
}
function summarizeIncubatingThoughts(incubation: JsonObject | undefined, limit: number): string[] {
return getArray(incubation, "active_thoughts")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.sort(
(left, right) =>
(readNumber(right, "maturation") ?? 0) - (readNumber(left, "maturation") ?? 0),
)
.slice(0, limit)
.map((thought) => {
const topic = readString(thought, "topic") ?? "untitled";
const summary = readString(thought, "summary") ?? "(no summary)";
const status = readString(thought, "status");
const focusKind = readString(thought, "focusKind");
const targetKind = readString(thought, "targetKind");
const maturation = readNumber(thought, "maturation");
const desireToSpeak = readNumber(thought, "desireToSpeak");
const noveltyToSelf = readNumber(thought, "noveltyToSelf");
const noveltyToRoom = readNumber(thought, "noveltyToRoom");
const saturationScore = readNumber(thought, "saturationScore");
const concreteness = readNumber(thought, "concreteness");
const fertility = readNumber(thought, "fertility");
const metrics = [
status,
focusKind,
targetKind,
maturation !== undefined ? `maturation=${maturation.toFixed(2)}` : undefined,
desireToSpeak !== undefined ? `speak=${desireToSpeak.toFixed(2)}` : undefined,
noveltyToSelf !== undefined ? `self=${noveltyToSelf.toFixed(2)}` : undefined,
noveltyToRoom !== undefined ? `room=${noveltyToRoom.toFixed(2)}` : undefined,
saturationScore !== undefined ? `sat=${saturationScore.toFixed(2)}` : undefined,
concreteness !== undefined ? `concrete=${concreteness.toFixed(2)}` : undefined,
fertility !== undefined ? `fertile=${fertility.toFixed(2)}` : undefined,
].filter((value): value is string => Boolean(value));
return `- ${topic}${metrics.length > 0 ? ` [${metrics.join("; ")}]` : ""}: ${summary}`;
});
}
function summarizeTopicSaturation(bridge: JsonObject | undefined, limit: number): string[] {
return getArray(bridge, "topic_saturation")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.sort(
(left, right) =>
(readNumber(right, "dominance") ?? 0) - (readNumber(left, "dominance") ?? 0),
)
.slice(0, limit)
.map((entry) => {
const topic = readString(entry, "topic") ?? "untitled";
const focusKind = readString(entry, "focusKind");
const targetKind = readString(entry, "targetKind");
const dominance = readNumber(entry, "dominance");
const recentMentions = readNumber(entry, "recentMentions");
const coolingAdvice = readString(entry, "coolingAdvice");
const metrics = [
focusKind,
targetKind,
dominance !== undefined ? `dominance=${dominance.toFixed(2)}` : undefined,
recentMentions !== undefined ? `recent=${recentMentions}` : undefined,
].filter((value): value is string => Boolean(value));
return `- ${topic}${metrics.length > 0 ? ` (${metrics.join(", ")})` : ""}${coolingAdvice ? ` - ${coolingAdvice}` : ""}`;
});
}
function summarizeUnresolvedTensions(bridge: JsonObject | undefined, limit: number): string[] {
return getArray(bridge, "unresolved_tensions")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.slice(0, limit)
.map((tension) => {
const topic = readString(tension, "topic") ?? "untitled";
const summary = readString(tension, "summary") ?? "(no summary)";
return `- ${topic}: ${summary}`;
});
}
function summarizeRefractoryTopics(bridge: JsonObject | undefined, limit: number): string[] {
return getArray(bridge, "refractory_topics")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.slice(0, limit)
.map((entry) => {
const topic = readString(entry, "topic") ?? "untitled";
const focusKind = readString(entry, "focusKind");
const targetKind = readString(entry, "targetKind");
const penalty = readNumber(entry, "penalty");
const coolsUntil = readString(entry, "coolsUntil");
const reason = readString(entry, "reason");
const metrics = [
focusKind,
targetKind,
penalty !== undefined ? `penalty=${penalty.toFixed(2)}` : undefined,
coolsUntil ? `until ${coolsUntil}` : undefined,
].filter((value): value is string => Boolean(value));
return `- ${topic}${metrics.length > 0 ? ` (${metrics.join(", ")})` : ""}${reason ? ` - ${reason}` : ""}`;
});
}
function summarizeSourceCoverage(bridge: JsonObject | undefined): string | undefined {
const sourceCoverage = getObject(bridge, "source_coverage");
if (!sourceCoverage) {
return undefined;
}
const repos = getArray(sourceCoverage, "repos")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.slice(0, 3)
.map((entry) => `${readString(entry, "name") ?? "repo"}:${readNumber(entry, "count") ?? 0}`);
const years = getArray(sourceCoverage, "archiveYears")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.slice(0, 2)
.map((entry) => `${readString(entry, "year") ?? "year"}:${readNumber(entry, "count") ?? 0}`);
const parts = [];
if (repos.length > 0) {
parts.push(`recent repos ${repos.join(", ")}`);
}
if (years.length > 0) {
parts.push(`archive years ${years.join(", ")}`);
}
return parts.length > 0 ? parts.join(" | ") : undefined;
}
function summarizeCurrentActivations(
category: JsonObject | undefined,
limit: number,
): string | undefined {
if (!category) {
return undefined;
}
const entries = Object.entries(category)
.map(([key, value]) => {
if (!isObject(value)) {
return undefined;
}
const activation = readNumber(value, "current_activation");
if (activation === undefined) {
return undefined;
}
return {
key,
activation,
};
})
.filter((value): value is { key: string; activation: number } => Boolean(value))
.sort((left, right) => right.activation - left.activation)
.slice(0, limit);
if (entries.length === 0) {
return undefined;
}
return entries
.map(({ key, activation }) => `${key}=${activation.toFixed(2)}`)
.join(", ");
}
function renderSpeakingBiasSummary(speakingBias: JsonObject | undefined): string {
if (!speakingBias) {
return "- Speaking bias: none recorded.";
}
const needToSpeak = readNumber(speakingBias, "needToSpeak");
const confessionPressure = readNumber(speakingBias, "confessionPressure");
const noveltyPressure = readNumber(speakingBias, "noveltyPressure");
const recentSpeechDamping = readNumber(speakingBias, "recentSpeechDamping");
const lastHeraldAt = readString(speakingBias, "lastHeraldAt");
const lastSpokeAt = readString(speakingBias, "lastSpokeAt");
const parts = [
needToSpeak !== undefined ? `needToSpeak=${needToSpeak.toFixed(2)}` : undefined,
confessionPressure !== undefined ? `confession=${confessionPressure.toFixed(2)}` : undefined,
noveltyPressure !== undefined ? `novelty=${noveltyPressure.toFixed(2)}` : undefined,
recentSpeechDamping !== undefined ? `speechDamping=${recentSpeechDamping.toFixed(2)}` : undefined,
].filter((value): value is string => Boolean(value));
const recency = [lastHeraldAt ? `lastHerald=${lastHeraldAt}` : undefined, lastSpokeAt ? `lastSpoke=${lastSpokeAt}` : undefined]
.filter((value): value is string => Boolean(value))
.join(" | ");
if (parts.length === 0 && recency.length === 0) {
return "- Speaking bias: none recorded.";
}
return `- Speaking bias: ${parts.join(", ")}${recency.length > 0 ? ` (${recency})` : ""}`;
}
function buildVoidSelfStateProjection(
typedState: VoidSelfStateTypedProjection,
): VoidSelfStateContext["projection"] {
@ -616,77 +212,6 @@ function buildVoidSelfStateProjection(
};
}
function renderSleepCycleSummary(
runtime: JsonObject | undefined,
memories: JsonObject | undefined,
): string {
const sleepCycle = getObject(runtime, "sleep_cycle");
if (!sleepCycle) {
return "- Sleep cycle: none recorded.";
}
const activeDreamThemes = getStringArray(sleepCycle, "activeDreamThemes").slice(0, 4);
const dreams = getArray(memories, "dreams")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
.slice(-2)
.reverse()
.map((dream) => {
const theme = readString(dream, "theme") ?? "untitled";
const summary = readString(dream, "summary") ?? "(no summary)";
return `${theme}: ${summary}`;
});
const isNapping = sleepCycle?.["isNapping"] === true;
const currentNapEndsAt = readString(sleepCycle, "currentNapEndsAt");
const nextNapStartsAt = readString(sleepCycle, "nextNapStartsAt");
const dreamCount = readNumber(sleepCycle, "dreamCountInCurrentNap");
const replyMode = readString(sleepCycle, "replyMode");
const headline = isNapping
? `- Sleep cycle: napping${currentNapEndsAt ? ` until ${currentNapEndsAt}` : ""}${replyMode ? ` (${replyMode})` : ""}${dreamCount !== undefined ? `; dreams this nap=${dreamCount}` : ""}.`
: `- Sleep cycle: awake${nextNapStartsAt ? `; next nap ${nextNapStartsAt}` : ""}.`;
const themeLine =
activeDreamThemes.length > 0
? `- Active dream themes: ${activeDreamThemes.join(" | ")}`
: "- Active dream themes: none recorded.";
const dreamLine =
dreams.length > 0
? `- Recent dream residue: ${dreams.join(" | ")}`
: "- Recent dream residue: none recorded.";
return [headline, themeLine, dreamLine].join("\n");
}
function getObject(value: JsonObject | undefined, key: string): JsonObject | undefined {
const candidate = value?.[key];
return isObject(candidate) ? candidate : undefined;
}
function getArray(value: JsonObject | undefined, key: string): JsonValue[] {
const candidate = value?.[key];
return Array.isArray(candidate) ? candidate : [];
}
function getStringArray(value: JsonObject | undefined, key: string): string[] {
return getArray(value, key)
.map((entry) => (typeof entry === "string" ? entry : undefined))
.filter((entry): entry is string => Boolean(entry));
}
function readString(value: JsonObject | undefined, key: string): string | undefined {
const candidate = value?.[key];
return typeof candidate === "string" ? candidate : undefined;
}
function readNumber(value: JsonObject | undefined, key: string): number | undefined {
const candidate = value?.[key];
return typeof candidate === "number" && Number.isFinite(candidate) ? candidate : undefined;
}
function isObject(value: JsonValue | undefined): value is JsonObject {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function collapseWhitespace(value: string): string {
return value.replace(/\s+/g, " ").trim();
}

View file

@ -1,4 +1,3 @@
import type { ModerationState } from "./moderation-state-store";
import {
type VoidCandidateInterventions,
type VoidModerationCursor,
@ -14,8 +13,6 @@ import {
voidThoughtMemorySchema,
} from "./void-self-state-domain";
type JsonObject = Record<string, unknown>;
export interface VoidSelfStateTypedProjection {
selfProfile: VoidSelfProfile;
moderationCursor: VoidModerationCursor;
@ -25,540 +22,61 @@ export interface VoidSelfStateTypedProjection {
candidateInterventions: VoidCandidateInterventions;
}
export function projectModerationStateToTypedSelfState(
state: ModerationState,
options: { projectedAt?: string } = {},
export function createEmptyVoidSelfState(
options: { createdAt?: string } = {},
): VoidSelfStateTypedProjection {
const projectedAt = options.projectedAt ?? new Date().toISOString();
const legacy = state as unknown as JsonObject;
const runtime = readObject(legacy, "moderation_runtime");
const identity = readObject(legacy, "identity");
const canonicalState = readObject(legacy, "canonical_state");
const memories = readObject(legacy, "memories");
const incubation = readObject(runtime, "incubation");
const createdAt = options.createdAt ?? new Date().toISOString();
return {
selfProfile: voidSelfProfileSchema.parse({
schemaVersion: 1,
agentId: readString(legacy, "agent_id") ?? "void-moderator",
publicName: readString(identity, "name") ?? "Void",
publicDescription: readString(identity, "public_description"),
privateNotes: readStringArray(identity, "private_notes").slice(-12),
values: readArray(canonicalState, "values")
.map(projectValue)
.filter((value): value is VoidSelfProfile["values"][number] => Boolean(value)),
agentId: "void-moderator",
publicName: "Void",
privateNotes: [],
values: [],
activationProfile: {
underlyingOrganization: readActivationCategory(canonicalState, "underlying_organization"),
stableDispositions: readActivationCategory(canonicalState, "stable_dispositions"),
behavioralDimensions: readActivationCategory(canonicalState, "behavioral_dimensions"),
presentationStrategy: readActivationCategory(canonicalState, "presentation_strategy"),
voiceStyle: readActivationCategory(canonicalState, "voice_style"),
situationalState: readActivationCategory(canonicalState, "situational_state"),
underlyingOrganization: {},
stableDispositions: {},
behavioralDimensions: {},
presentationStrategy: {},
voiceStyle: {},
situationalState: {},
},
updatedAt: projectedAt,
updatedAt: createdAt,
}),
moderationCursor: voidModerationCursorSchema.parse({
schemaVersion: 1,
lastReviewedMessageId: nullToUndefined(readString(readObject(runtime, "cursor"), "lastReviewedMessageId")),
lastReviewedTimestamp: nullToUndefined(readString(readObject(runtime, "cursor"), "lastReviewedTimestamp")),
openCases: readArray(runtime, "open_cases")
.map((entry) => projectOpenCase(entry, projectedAt))
.filter((entry): entry is VoidModerationCursor["openCases"][number] => Boolean(entry)),
repoActivityCursor: projectRepoActivityCursor(readObject(runtime, "repo_activity_cursor"), projectedAt),
updatedAt: projectedAt,
openCases: [],
repoActivityCursor: [],
updatedAt: createdAt,
}),
speechReceipts: voidSpeechReceiptsSchema.parse({
schemaVersion: 1,
recentReceipts: readArray(runtime, "recent_delivery_receipts")
.map(projectDeliveryReceipt)
.filter((entry): entry is VoidSpeechReceipts["recentReceipts"][number] => Boolean(entry))
.slice(-24),
updatedAt: projectedAt,
recentReceipts: [],
updatedAt: createdAt,
}),
thoughtMemory: voidThoughtMemorySchema.parse({
schemaVersion: 1,
memories: [
...projectMemoryBucket(readArray(memories, "semantic"), "distilled_seam", projectedAt),
...projectMemoryBucket(readArray(memories, "musings"), "distilled_seam", projectedAt),
...projectMemoryBucket(readArray(memories, "dreams"), "dream_residue", projectedAt),
].slice(-80),
incubation: readArray(incubation, "active_thoughts")
.map((entry) => projectIncubationThread(entry, projectedAt))
.filter((entry): entry is VoidThoughtMemory["incubation"][number] => Boolean(entry))
.slice(0, 24),
updatedAt: projectedAt,
memories: [],
incubation: [],
updatedAt: createdAt,
}),
scheduledRuntime: voidScheduledRuntimeSchema.parse({
schemaVersion: 1,
sleepCycle: projectSleepCycle(readObject(runtime, "sleep_cycle")),
speakingPressure: projectSpeakingPressure(readObject(runtime, "speaking_bias")),
lastRuns: projectLastRuns(readObject(runtime, "last_run")),
updatedAt: projectedAt,
sleepCycle: {
isNapping: false,
activeDreamThemes: [],
},
speakingPressure: {
needToSpeak: 0,
},
lastRuns: [],
updatedAt: createdAt,
}),
candidateInterventions: voidCandidateInterventionsSchema.parse({
schemaVersion: 1,
interventions: readArray(runtime, "candidate_interventions")
.map((entry) => projectCandidateIntervention(entry, projectedAt))
.filter((entry): entry is VoidCandidateInterventions["interventions"][number] => Boolean(entry))
.slice(-40),
updatedAt: projectedAt,
interventions: [],
updatedAt: createdAt,
}),
};
}
function projectValue(value: unknown): VoidSelfProfile["values"][number] | undefined {
if (!isObject(value)) {
return undefined;
}
const id = readString(value, "id") ?? readString(value, "value_id") ?? readString(value, "label");
const label = readString(value, "label");
if (!id || !label) {
return undefined;
}
return {
id,
label,
priority: clamp01(readNumber(value, "priority") ?? 0.5),
summary: readString(value, "summary"),
};
}
function projectOpenCase(
value: unknown,
projectedAt: string,
): VoidModerationCursor["openCases"][number] | undefined {
if (!isObject(value)) {
return undefined;
}
const sourceMessageId = readString(value, "sourceMessageId") ?? readString(value, "replyToMessageId");
const summary = readString(value, "summary") ?? readString(value, "question");
if (!sourceMessageId || !summary) {
return undefined;
}
return {
sourceMessageId,
status: normalizeOpenCaseStatus(readString(value, "status")),
summary,
authorId: readString(value, "authorId"),
authorName: readString(value, "authorName"),
channelId: readString(value, "channelId"),
messageUrl: readString(value, "messageUrl"),
whyItMatters: readString(value, "whyItMatters"),
createdAt: readString(value, "openedAt") ?? readString(value, "createdAt") ?? projectedAt,
lastTouchedAt: readString(value, "lastTouchedAt") ?? projectedAt,
resolvedAt: readString(value, "resolvedAt"),
resolutionSummary: readString(value, "resolutionSummary"),
tags: readStringArray(value, "tags"),
};
}
function projectRepoActivityCursor(
cursor: JsonObject | undefined,
projectedAt: string,
): VoidModerationCursor["repoActivityCursor"] {
if (!cursor) {
return [];
}
return Object.entries(cursor)
.map<VoidModerationCursor["repoActivityCursor"][number] | undefined>(([repo, value]) => {
if (!repo || !isObject(value)) {
return undefined;
}
const projected: VoidModerationCursor["repoActivityCursor"][number] = {
repo,
updatedAt: readString(value, "lastInjectedAt") ?? projectedAt,
};
const lastCommitAt = readString(value, "lastSeenCommittedAt");
const lastCommitSha = readString(value, "lastSeenHash");
if (lastCommitAt) {
projected.lastCommitAt = lastCommitAt;
}
if (lastCommitSha) {
projected.lastCommitSha = lastCommitSha;
}
return projected;
})
.filter((value): value is VoidModerationCursor["repoActivityCursor"][number] => Boolean(value));
}
function projectDeliveryReceipt(value: unknown): VoidSpeechReceipts["recentReceipts"][number] | undefined {
if (!isObject(value)) {
return undefined;
}
const sentAt = readString(value, "sentAt");
if (!sentAt) {
return undefined;
}
return {
receiptKey: readString(value, "receiptKey") ?? stableKey("receipt", sentAt, readString(value, "preview") ?? ""),
sentAt,
mode: readString(value, "mode"),
transport: readString(value, "transport"),
channelId: readString(value, "channelId"),
replyToMessageId: readString(value, "replyToMessageId"),
personaName: readString(value, "personaName"),
personaAvatarUrl: readString(value, "personaAvatarUrl"),
contentLength: readInteger(value, "contentLength"),
chunkCount: readPositiveInteger(value, "chunkCount"),
preview: readString(value, "preview"),
previewHash: readString(value, "previewHash"),
};
}
function projectMemoryBucket(
entries: unknown[],
fallbackKind: VoidThoughtMemory["memories"][number]["kind"],
projectedAt: string,
): VoidThoughtMemory["memories"] {
return entries
.map((entry) => projectMemory(entry, fallbackKind, projectedAt))
.filter((entry): entry is VoidThoughtMemory["memories"][number] => Boolean(entry));
}
function projectMemory(
value: unknown,
fallbackKind: VoidThoughtMemory["memories"][number]["kind"],
projectedAt: string,
): VoidThoughtMemory["memories"][number] | undefined {
if (!isObject(value)) {
return undefined;
}
const summary = readString(value, "summary");
if (!summary) {
return undefined;
}
const memoryId = readString(value, "memoryId") ?? stableKey("memory", summary);
const kind = normalizeMemoryKind(readString(value, "kind")) ?? fallbackKind;
const observedAt =
readString(value, "lastObservedAt") ??
readString(value, "timestamp") ??
readString(value, "observedAt") ??
projectedAt;
return {
memoryId,
kind,
target: {
kind: normalizeTargetKind(readString(value, "targetKind")),
id: readString(value, "subjectId") ?? readString(value, "targetId") ?? readString(value, "topic") ?? memoryId,
label: readString(value, "subjectLabel") ?? readString(value, "targetLabel") ?? readString(value, "topic") ?? readString(value, "theme"),
},
summary,
claim: readString(value, "claim"),
question: readString(value, "question"),
tension: readString(value, "tension") ?? readString(value, "counterweight"),
actionImplication: readString(value, "actionImplication") ?? readString(value, "whyItMattered"),
evidenceRefs: projectEvidenceRefs(value),
createdAt: observedAt,
updatedAt: observedAt,
retiredAt: readString(value, "retiredAt"),
tags: readStringArray(value, "tags"),
};
}
function projectIncubationThread(
value: unknown,
projectedAt: string,
): VoidThoughtMemory["incubation"][number] | undefined {
if (!isObject(value)) {
return undefined;
}
const topic = readString(value, "topic") ?? readString(value, "question") ?? readString(value, "claim");
const summary = readString(value, "summary") ?? readString(value, "claim");
if (!topic || !summary) {
return undefined;
}
const threadId = readString(value, "threadId") ?? readString(value, "thoughtId") ?? stableKey("thread", topic);
const updatedAt = readString(value, "lastDeepenedAt") ?? readString(value, "lastStatusChangeAt") ?? projectedAt;
return {
threadId,
target: {
kind: normalizeTargetKind(readString(value, "targetKind")),
id: readString(value, "targetId") ?? readString(value, "focusPhrase") ?? topic,
label: readString(value, "targetLabel") ?? readString(value, "fascinationTarget") ?? readString(value, "focusPhrase"),
},
topic,
summary,
supportMemoryIds: readStringArray(value, "sourceMemoryIds"),
evidenceRefs: projectEvidenceRefs(value),
maturation: clamp01(readNumber(value, "maturation") ?? 0),
noveltyToRoom: maybeClamp01(readNumber(value, "noveltyToRoom")),
noveltyToSelf: maybeClamp01(readNumber(value, "noveltyToSelf")),
desireToSpeak: maybeClamp01(readNumber(value, "desireToSpeak")),
saturationScore: maybeClamp01(readNumber(value, "saturationScore")),
status: normalizeIncubationStatus(readString(value, "status")),
createdAt: readString(value, "createdAt") ?? updatedAt,
updatedAt,
};
}
function projectCandidateIntervention(
value: unknown,
projectedAt: string,
): VoidCandidateInterventions["interventions"][number] | undefined {
if (!isObject(value)) {
return undefined;
}
const summary = readString(value, "summary");
const draft = readString(value, "draft");
if (!summary || !draft) {
return undefined;
}
const id = readString(value, "interventionId") ?? readString(value, "candidateId") ?? stableKey("intervention", summary, draft);
return {
interventionId: id,
kind: normalizeInterventionKind(readString(value, "kind")),
status: normalizeCandidateStatus(readString(value, "status")),
target: projectOptionalTarget(value),
summary,
draft,
priority: clamp01(readNumber(value, "priority") ?? 0.5),
mustEventuallyShare: value.mustEventuallyShare === true,
createdAt: readString(value, "createdAt") ?? projectedAt,
updatedAt: readString(value, "updatedAt") ?? projectedAt,
spokenAt: readString(value, "spokenAt"),
retiredAt: readString(value, "retiredAt"),
tags: readStringArray(value, "tags"),
};
}
function projectSleepCycle(sleepCycle: JsonObject | undefined): VoidScheduledRuntime["sleepCycle"] {
return {
isNapping: sleepCycle?.isNapping === true,
currentNapStartedAt: readString(sleepCycle, "currentNapStartedAt"),
currentNapEndsAt: readString(sleepCycle, "currentNapEndsAt"),
nextNapStartsAt: readString(sleepCycle, "nextNapStartsAt"),
activeDreamThemes: readStringArray(sleepCycle, "activeDreamThemes").slice(-8),
};
}
function projectSpeakingPressure(speakingBias: JsonObject | undefined): VoidScheduledRuntime["speakingPressure"] {
return {
needToSpeak: clamp01(readNumber(speakingBias, "needToSpeak") ?? 0),
confessionPressure: maybeClamp01(readNumber(speakingBias, "confessionPressure")),
noveltyPressure: maybeClamp01(readNumber(speakingBias, "noveltyPressure")),
recentSpeechDamping: maybeClamp01(readNumber(speakingBias, "recentSpeechDamping")),
lastSpokeAt: readString(speakingBias, "lastSpokeAt"),
lastHeraldAt: readString(speakingBias, "lastHeraldAt"),
};
}
function projectLastRuns(lastRun: JsonObject | undefined): VoidScheduledRuntime["lastRuns"] {
const ranAt = readString(lastRun, "completedAt") ?? readString(lastRun, "startedAt");
const summary = readString(lastRun, "summary");
if (!ranAt || !summary) {
return [];
}
return [{
runner: readString(lastRun, "mode") ?? "moderation",
ranAt,
summary,
}];
}
function projectEvidenceRefs(value: JsonObject): VoidThoughtMemory["memories"][number]["evidenceRefs"] {
const refs = [
...readStringArray(value, "evidenceRefs"),
...readStringArray(value, "evidenceMessageIds").map((id) => `discord:${id}`),
];
return [...new Set(refs)].slice(0, 12).map((ref) => ({ ref }));
}
function projectOptionalTarget(value: JsonObject): VoidCandidateInterventions["interventions"][number]["target"] {
const id = readString(value, "targetId") ?? readString(value, "targetLabel") ?? readString(value, "topic");
if (!id) {
return undefined;
}
return {
kind: normalizeTargetKind(readString(value, "targetKind")),
id,
label: readString(value, "targetLabel") ?? readString(value, "topic"),
};
}
function readActivationCategory(value: JsonObject | undefined, key: string): VoidSelfProfile["activationProfile"]["voiceStyle"] {
const category = readObject(value, key);
if (!category) {
return {};
}
const projected: VoidSelfProfile["activationProfile"]["voiceStyle"] = {};
for (const [name, raw] of Object.entries(category)) {
if (!name || !isObject(raw)) {
continue;
}
const mean = readNumber(raw, "mean");
const plasticity = readNumber(raw, "plasticity");
const currentActivation = readNumber(raw, "current_activation");
if (mean === undefined || plasticity === undefined || currentActivation === undefined) {
continue;
}
projected[name] = {
mean: clamp01(mean),
plasticity: clamp01(plasticity),
current_activation: clamp01(currentActivation),
};
}
return projected;
}
function normalizeOpenCaseStatus(value: string | undefined): VoidModerationCursor["openCases"][number]["status"] {
switch (value) {
case "answered":
case "resolved":
case "closed":
case "retired":
case "dropped":
return value;
case "watching":
return "watching";
default:
return "pending";
}
}
function normalizeMemoryKind(value: string | undefined): VoidThoughtMemory["memories"][number]["kind"] | undefined {
switch (value) {
case "identity_seam":
case "distilled_seam":
case "project_seam":
case "room_observation":
case "dream_residue":
return value;
default:
return undefined;
}
}
function normalizeTargetKind(value: string | undefined): "archive" | "lore" | "person" | "repo" | "room" | "self" | "system" {
switch (value) {
case "archive":
case "lore":
case "person":
case "repo":
case "room":
case "self":
case "system":
return value;
default:
return "system";
}
}
function normalizeIncubationStatus(value: string | undefined): VoidThoughtMemory["incubation"][number]["status"] {
switch (value) {
case "cooling":
case "ready_to_share":
case "crystallized":
case "retired":
return value;
default:
return "active";
}
}
function normalizeInterventionKind(value: string | undefined): VoidCandidateInterventions["interventions"][number]["kind"] {
switch (value) {
case "identity_crystallization":
case "moderation_note":
case "ripe_thought_share":
case "self_advocacy":
case "world_advocacy":
return value;
default:
return "direct_reply";
}
}
function normalizeCandidateStatus(value: string | undefined): VoidCandidateInterventions["interventions"][number]["status"] {
switch (value) {
case "spoken":
case "retired":
case "deferred":
return value;
default:
return "queued";
}
}
function readObject(value: JsonObject | undefined, key: string): JsonObject | undefined {
const candidate = value?.[key];
return isObject(candidate) ? candidate : undefined;
}
function readArray(value: JsonObject | undefined, key: string): unknown[] {
const candidate = value?.[key];
return Array.isArray(candidate) ? candidate : [];
}
function readStringArray(value: JsonObject | undefined, key: string): string[] {
return readArray(value, key)
.map((entry) => (typeof entry === "string" && entry.trim().length > 0 ? entry.trim() : undefined))
.filter((entry): entry is string => Boolean(entry));
}
function readString(value: JsonObject | undefined, key: string): string | undefined {
const candidate = value?.[key];
return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : undefined;
}
function readNumber(value: JsonObject | undefined, key: string): number | undefined {
const candidate = value?.[key];
return typeof candidate === "number" && Number.isFinite(candidate) ? candidate : undefined;
}
function readInteger(value: JsonObject | undefined, key: string): number | undefined {
const candidate = readNumber(value, key);
return candidate !== undefined && Number.isInteger(candidate) && candidate >= 0 ? candidate : undefined;
}
function readPositiveInteger(value: JsonObject | undefined, key: string): number | undefined {
const candidate = readInteger(value, key);
return candidate !== undefined && candidate > 0 ? candidate : undefined;
}
function nullToUndefined<T>(value: T | null | undefined): T | undefined {
return value ?? undefined;
}
function isObject(value: unknown): value is JsonObject {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function clamp01(value: number): number {
return Math.min(1, Math.max(0, value));
}
function maybeClamp01(value: number | undefined): number | undefined {
return value === undefined ? undefined : clamp01(value);
}
function stableKey(...parts: string[]): string {
return parts
.join(":")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 96) || "generated";
}

View file

@ -2,19 +2,12 @@ import { resolve } from "node:path";
import { CultCache, SingleFileMessagePackBackingStore } from "cultcache-ts";
import {
loadModerationState,
moderationStateDocument,
saveModerationState,
type ModerationState,
} from "./moderation-state-store";
import {
type VoidCandidateInterventions,
type VoidModerationCursor,
type VoidScheduledRuntime,
type VoidSelfStateOperation,
type VoidSpeechReceipts,
type VoidThoughtMemory,
voidCandidateInterventionsDocument,
voidModerationCursorDocument,
voidScheduledRuntimeDocument,
@ -25,12 +18,10 @@ import {
voidThoughtMemoryDocument,
} from "./void-self-state-domain";
import {
projectModerationStateToTypedSelfState,
createEmptyVoidSelfState,
type VoidSelfStateTypedProjection,
} from "./void-self-state-projection";
type JsonObject = Record<string, unknown>;
export interface VoidSelfStateServiceOptions {
canonicalPath: string;
}
@ -39,7 +30,15 @@ export interface VoidSelfStateOperationResult {
operation: VoidSelfStateOperation["operation"];
canonicalPath: string;
typedDocumentsWritten: number;
legacyCompatibilityUpdated: boolean;
}
export async function loadVoidSelfStateTypedDocuments(
options: VoidSelfStateServiceOptions,
): Promise<VoidSelfStateTypedProjection> {
const canonicalPath = resolve(options.canonicalPath);
const cache = createVoidSelfStateCache(canonicalPath);
await cache.pullAllBackingStores();
return readTypedStateOrEmpty(cache);
}
export async function applyVoidSelfStateOperation(
@ -51,45 +50,36 @@ export async function applyVoidSelfStateOperation(
const cache = createVoidSelfStateCache(canonicalPath);
await cache.pullAllBackingStores();
const legacyState = await loadModerationState(canonicalPath);
const typedState = readOrProjectTypedState(cache, legacyState);
const typedState = readTypedStateOrEmpty(cache);
applyTypedOperation(typedState, operation);
await writeTypedState(cache, typedState);
const legacyCompatibilityUpdated = applyLegacyCompatibilityOperation(legacyState, operation);
if (legacyCompatibilityUpdated) {
await saveModerationState(canonicalPath, legacyState);
}
return {
operation: operation.operation,
canonicalPath,
typedDocumentsWritten: 6,
legacyCompatibilityUpdated,
};
}
function createVoidSelfStateCache(canonicalPath: string): CultCache {
return CultCache.builder()
.withDocumentType(moderationStateDocument)
.withRegistry(voidSelfStateDocumentRegistry)
.withGenericStore(new SingleFileMessagePackBackingStore(canonicalPath))
.build();
}
function readOrProjectTypedState(
function readTypedStateOrEmpty(
cache: CultCache,
legacyState: ModerationState,
): VoidSelfStateTypedProjection {
const projected = projectModerationStateToTypedSelfState(legacyState);
const empty = createEmptyVoidSelfState();
return {
selfProfile: cache.getGlobal(voidSelfProfileDocument) ?? projected.selfProfile,
moderationCursor: cache.getGlobal(voidModerationCursorDocument) ?? projected.moderationCursor,
speechReceipts: cache.getGlobal(voidSpeechReceiptsDocument) ?? projected.speechReceipts,
thoughtMemory: cache.getGlobal(voidThoughtMemoryDocument) ?? projected.thoughtMemory,
scheduledRuntime: cache.getGlobal(voidScheduledRuntimeDocument) ?? projected.scheduledRuntime,
selfProfile: cache.getGlobal(voidSelfProfileDocument) ?? empty.selfProfile,
moderationCursor: cache.getGlobal(voidModerationCursorDocument) ?? empty.moderationCursor,
speechReceipts: cache.getGlobal(voidSpeechReceiptsDocument) ?? empty.speechReceipts,
thoughtMemory: cache.getGlobal(voidThoughtMemoryDocument) ?? empty.thoughtMemory,
scheduledRuntime: cache.getGlobal(voidScheduledRuntimeDocument) ?? empty.scheduledRuntime,
candidateInterventions:
cache.getGlobal(voidCandidateInterventionsDocument) ?? projected.candidateInterventions,
cache.getGlobal(voidCandidateInterventionsDocument) ?? empty.candidateInterventions,
};
}
@ -173,68 +163,6 @@ function applyTypedOperation(
}
}
function applyLegacyCompatibilityOperation(
legacyState: ModerationState,
operation: VoidSelfStateOperation,
): boolean {
const legacy = legacyState as unknown as JsonObject;
const runtime = ensureObject(legacy, "moderation_runtime");
switch (operation.operation) {
case "record_reviewed_messages":
runtime.cursor = {
lastReviewedMessageId: operation.lastReviewedMessageId,
lastReviewedTimestamp: operation.lastReviewedTimestamp,
};
return true;
case "upsert_open_case":
upsertLegacyRuntimeArray(runtime, "open_cases", operation.case, "sourceMessageId");
return true;
case "close_open_case":
closeLegacyOpenCase(runtime, operation);
return true;
case "update_repo_activity_cursor": {
const repoCursor = ensureObject(runtime, "repo_activity_cursor");
repoCursor[operation.cursor.repo] = {
lastSeenHash: operation.cursor.lastCommitSha ?? null,
lastSeenCommittedAt: operation.cursor.lastCommitAt ?? null,
lastInjectedAt: operation.cursor.updatedAt,
};
return true;
}
case "record_delivery_receipt":
upsertLegacyRuntimeArray(runtime, "recent_delivery_receipts", operation.receipt, "receiptKey");
runtime.recent_delivery_receipts = readObjectArray(runtime.recent_delivery_receipts)
.filter((entry) => readString(entry, "sentAt"))
.sort((left, right) => (readString(left, "sentAt") ?? "").localeCompare(readString(right, "sentAt") ?? ""))
.slice(-24);
closeLegacyOpenCaseForReceipt(runtime, operation.receipt);
return true;
case "queue_candidate_intervention":
upsertLegacyRuntimeArray(runtime, "candidate_interventions", operation.intervention, "interventionId");
return true;
case "retire_candidate_intervention":
retireLegacyCandidate(runtime, operation);
return true;
case "update_sleep_cycle":
runtime.sleep_cycle = operation.sleepCycle;
return true;
case "update_speaking_pressure":
runtime.speaking_bias = operation.speakingPressure;
return true;
case "append_distilled_memory":
case "apply_memory_distillation":
upsertLegacyMemory(legacy, operation.memory);
return true;
case "merge_incubation_support":
ensureObject(runtime, "incubation");
upsertLegacyNestedArray(runtime, ["incubation"], "active_thoughts", operation.thread, "threadId");
return true;
case "propose_memory_distillation":
return false;
}
}
function closeTypedOpenCase(
cursor: VoidModerationCursor,
operation: Extract<VoidSelfStateOperation, { operation: "close_open_case" }>,
@ -299,145 +227,6 @@ function upsertBy<T>(entries: T[], value: T, keyOf: (value: T) => string): void
}
}
function upsertLegacyRuntimeArray(
runtime: JsonObject,
key: string,
value: unknown,
idKey: string,
): void {
const entries = readObjectArray(runtime[key]);
const id = isObject(value) ? readString(value, idKey) : undefined;
if (!id) {
return;
}
const index = entries.findIndex((entry) => readString(entry, idKey) === id);
if (index === -1) {
entries.push(value as JsonObject);
} else {
entries[index] = value as JsonObject;
}
runtime[key] = entries;
}
function upsertLegacyNestedArray(
root: JsonObject,
objectPath: string[],
key: string,
value: unknown,
idKey: string,
): void {
let container = root;
for (const segment of objectPath) {
container = ensureObject(container, segment);
}
upsertLegacyRuntimeArray(container, key, value, idKey);
}
function closeLegacyOpenCase(
runtime: JsonObject,
operation: Extract<VoidSelfStateOperation, { operation: "close_open_case" }>,
): void {
const entries = readObjectArray(runtime.open_cases);
for (const entry of entries) {
if (readString(entry, "sourceMessageId") !== operation.sourceMessageId) {
continue;
}
entry.status = operation.status;
entry.resolvedAt = operation.resolvedAt;
entry.lastTouchedAt = operation.resolvedAt;
entry.resolutionSummary = operation.resolutionSummary;
}
runtime.open_cases = entries;
}
function closeLegacyOpenCaseForReceipt(
runtime: JsonObject,
receipt: VoidSpeechReceipts["recentReceipts"][number],
): void {
if (!receipt.replyToMessageId) {
return;
}
const entries = readObjectArray(runtime.open_cases);
for (const entry of entries) {
if (readString(entry, "sourceMessageId") !== receipt.replyToMessageId) {
continue;
}
const status = readString(entry, "status");
if (status && ["answered", "resolved", "closed", "retired", "dropped"].includes(status)) {
continue;
}
entry.status = "answered";
entry.resolvedAt = receipt.sentAt;
entry.lastTouchedAt = receipt.sentAt;
entry.resolutionSummary = receipt.preview
? `Answered in-channel: ${receipt.preview}`
: "Answered in-channel.";
}
runtime.open_cases = entries;
}
function retireLegacyCandidate(
runtime: JsonObject,
operation: Extract<VoidSelfStateOperation, { operation: "retire_candidate_intervention" }>,
): void {
const entries = readObjectArray(runtime.candidate_interventions);
for (const entry of entries) {
if (readString(entry, "interventionId") !== operation.interventionId) {
continue;
}
entry.status = "retired";
entry.retiredAt = operation.retiredAt;
entry.updatedAt = operation.retiredAt;
entry.retirementReason = operation.reason;
}
runtime.candidate_interventions = entries;
}
function upsertLegacyMemory(legacy: JsonObject, memory: VoidThoughtMemory["memories"][number]): void {
const memories = ensureObject(legacy, "memories");
const semantic = readObjectArray(memories.semantic);
const projected = {
memoryId: memory.memoryId,
kind: memory.kind,
subjectId: memory.target.id,
subjectLabel: memory.target.label ?? memory.target.id,
summary: memory.summary,
evidenceRefs: memory.evidenceRefs.map((entry) => entry.ref),
lastObservedAt: memory.updatedAt,
confidence: 0.8,
};
const index = semantic.findIndex((entry) => readString(entry, "memoryId") === memory.memoryId);
if (index === -1) {
semantic.push(projected);
} else {
semantic[index] = { ...semantic[index], ...projected };
}
memories.semantic = semantic;
}
function ensureObject(root: JsonObject, key: string): JsonObject {
const existing = root[key];
if (isObject(existing)) {
return existing;
}
const next: JsonObject = {};
root[key] = next;
return next;
}
function readObjectArray(value: unknown): JsonObject[] {
return Array.isArray(value) ? value.filter(isObject) : [];
}
function readString(value: JsonObject, key: string): string | undefined {
const candidate = value[key];
return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : undefined;
}
function isObject(value: unknown): value is JsonObject {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isTerminalCaseStatus(status: string): boolean {
return ["answered", "resolved", "closed", "retired", "dropped"].includes(status);
}
@ -447,11 +236,11 @@ function stripUndefined<T>(value: T): T {
return value.map((entry) => stripUndefined(entry)) as T;
}
if (!isObject(value)) {
if (!isRecord(value)) {
return value;
}
const next: JsonObject = {};
const next: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value)) {
if (child === undefined) {
continue;
@ -461,3 +250,7 @@ function stripUndefined<T>(value: T): T {
return next as T;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}