Project legacy self-state into typed documents

This commit is contained in:
Meta Vens 2026-05-16 12:01:43 +01:00
commit 77ea82ffd6
7 changed files with 610 additions and 28 deletions

View file

@ -25,6 +25,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou
- The moderation/mood/private-self-state foundation does not. Treat it as the top architectural risk until JSON projection mutation and legacy mirrors are gone.
- The smallest coherent target is one polymorphic CultCache-backed state authority with typed document kinds plus typed mutation tools: agents propose small operations, and the state service validates/applies them. Whole-state JSON editing is rejected as a durable mutation path.
- Commit-one boundary naming is now in code at `packages/core/src/void-self-state-domain.ts`: it declares the global typed document kinds and strict operation payload schemas. Runtime behavior has not moved yet.
- Read-only projection is now in `packages/core/src/void-self-state-projection.ts`. `loadVoidSelfState` uses that typed projection for nap/reply-mode context while leaving the old richer prompt summary intact until typed documents explicitly own those details.
- Most of the deterministic cleanup in `scripts/void-memory-organ.mjs` is recent compensator cruft from failed attempts to manually clean an exploded state file. Do not preserve it as an earned organ. Architect the state boundary so that cleanup pile is unnecessary.
- Sleep/distillation must be rewritten with a meaning-preservation contract: concrete subject, claim/question, evidence refs, live tension, and future-action implication survive compression. Bulk can die. Meaning does not get put through the office shredder and called a dream.
- The owner Codex lane is no longer one swollen file; orchestration, runtime/parsing, rendering, and shared helpers are split under `packages/providers/src/owner-codex-*.ts`.
@ -83,8 +84,8 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou
## Likely Next Bounded Move
- Stop feature work on moderation, mood, agency, and public-lane behavior until the private-state boundary is rebuilt.
- First bounded move after the current commit: build read-only typed projections over the existing canonical moderation state, using the new document vocabulary without changing runtime mutation yet.
- Next cuts should delete unstable foundations early after projections exist: add the typed mutation CLI/service, move repo-activity cursor updates behind the typed store, replace whole-state agent JSON edits with operation output, remove `legacyJsonPath`/working-projection authority, then cut top-level mirror fields and cleanup code that only compensated for those broken boundaries.
- First bounded move after the current commit: add the typed mutation CLI/service for the operations already named in `void-self-state-domain.ts`.
- Next cuts should delete unstable foundations early after the mutation service exists: move repo-activity cursor updates behind the typed store, replace whole-state agent JSON edits with operation output, remove `legacyJsonPath`/working-projection authority, then cut top-level mirror fields and cleanup code that only compensated for those broken boundaries.
- Rebuild sleep/distillation before trusting it again. Fixture check: a memory like `AquariumSynthCSharp: Workflow cannot own the body` must survive sleep with its concrete subject, claim, evidence, tension, and implication intact.
- Do not build adapters around the JSON projection. That is how the heap learned to stand upright and ask for snacks.

View file

@ -12,3 +12,4 @@ export * from "./system-message-catalog";
export * from "./void-usage-rate-limiter";
export * from "./void-self-state-loader";
export * from "./void-self-state-domain";
export * from "./void-self-state-projection";

View file

@ -15,14 +15,20 @@ const timestampSchema = nonEmptyStringSchema;
const boundedTextSchema = z.string().trim().min(1).max(4000);
const taggedScalarSchema = z.union([z.string(), z.number(), z.boolean()]);
const evidenceRefSchema = z.object({
ref: nonEmptyStringSchema,
kind: z.string().trim().min(1).max(64).optional(),
summary: z.string().trim().max(1000).optional(),
}).strict();
const activationVectorSchema = z.object({
mean: z.number().min(0).max(1),
plasticity: z.number().min(0).max(1),
current_activation: z.number().min(0).max(1),
}).strict();
const activationCategorySchema = z.record(nonEmptyStringSchema, activationVectorSchema);
const thoughtTargetSchema = z.object({
kind: z.enum(["archive", "lore", "person", "repo", "room", "self", "system"]),
id: nonEmptyStringSchema,
@ -135,7 +141,14 @@ export const voidSelfProfileSchema = z.object({
priority: z.number().min(0).max(1),
summary: z.string().trim().max(1000).optional(),
}).strict()).default([]),
voice: z.record(nonEmptyStringSchema, taggedScalarSchema).default({}),
activationProfile: z.object({
underlyingOrganization: activationCategorySchema.default({}),
stableDispositions: activationCategorySchema.default({}),
behavioralDimensions: activationCategorySchema.default({}),
presentationStrategy: activationCategorySchema.default({}),
voiceStyle: activationCategorySchema.default({}),
situationalState: activationCategorySchema.default({}),
}).strict(),
updatedAt: timestampSchema,
}).strict();

View file

@ -4,7 +4,11 @@ import {
type VoidSelfStateContext,
} from "@voidbot/shared";
import { loadModerationState } from "./moderation-state-store";
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 };
@ -18,10 +22,10 @@ export async function loadVoidSelfState(
statePath: string,
options: LoadVoidSelfStateOptions = {},
): Promise<VoidSelfStateContext | undefined> {
let parsed: JsonObject;
let parsed: ModerationState;
try {
parsed = (await loadModerationState(statePath)) as unknown as JsonObject;
parsed = await loadModerationState(statePath);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
@ -32,12 +36,14 @@ export async function loadVoidSelfState(
throw error;
}
const projection = buildVoidSelfStateProjection(parsed);
const legacyProjection = parsed as unknown as JsonObject;
const typedProjection = projectModerationStateToTypedSelfState(parsed);
const projection = buildVoidSelfStateProjection(typedProjection);
return {
sourcePath: statePath,
loadedAt: new Date().toISOString(),
summary: renderVoidSelfStateSummary(parsed, options),
summary: renderVoidSelfStateSummary(legacyProjection, options),
projection,
};
}
@ -582,23 +588,19 @@ function renderSpeakingBiasSummary(speakingBias: JsonObject | undefined): string
return `- Speaking bias: ${parts.join(", ")}${recency.length > 0 ? ` (${recency})` : ""}`;
}
function buildVoidSelfStateProjection(state: JsonObject): VoidSelfStateContext["projection"] {
const memories = getObject(state, "memories");
const runtime = getObject(state, "moderation_runtime");
const sleepCycle = getObject(runtime, "sleep_cycle");
const dreamEntries = getArray(memories, "dreams")
.map((value) => (isObject(value) ? value : undefined))
.filter((value): value is JsonObject => Boolean(value))
function buildVoidSelfStateProjection(
typedState: VoidSelfStateTypedProjection,
): VoidSelfStateContext["projection"] {
const sleepCycle = typedState.scheduledRuntime.sleepCycle;
const dreamSummaries = typedState.thoughtMemory.memories
.filter((memory) => memory.kind === "dream_residue")
.slice(-3)
.reverse();
const dreamSummaries = dreamEntries
.map((entry) => readString(entry, "summary"))
.filter((entry): entry is string => Boolean(entry));
const activeDreamThemes = getStringArray(sleepCycle, "activeDreamThemes");
const isNapping = sleepCycle?.["isNapping"] === true;
const napStartedAt = readString(sleepCycle, "currentNapStartedAt") ?? readString(sleepCycle, "lastNapStartedAt");
const napEndsAt = readString(sleepCycle, "currentNapEndsAt");
const nextNapAt = readString(sleepCycle, "nextNapStartsAt");
.reverse()
.map((memory) => memory.summary);
const isNapping = sleepCycle.isNapping === true;
const napStartedAt = sleepCycle.currentNapStartedAt;
const napEndsAt = sleepCycle.currentNapEndsAt;
const nextNapAt = sleepCycle.nextNapStartsAt;
return {
mode: isNapping ? "napping" : "awake",
@ -606,7 +608,7 @@ function buildVoidSelfStateProjection(state: JsonObject): VoidSelfStateContext["
napStartedAt: isNapping ? napStartedAt : undefined,
napEndsAt: isNapping ? napEndsAt : undefined,
nextNapAt,
activeDreamThemes,
activeDreamThemes: sleepCycle.activeDreamThemes,
recentDreamSummaries: dreamSummaries,
replyDirective: isNapping
? "You are in a scheduled nap. Reply in brief, low-effort, half-dreaming mutters instead of doing full attentive service-work."

View file

@ -0,0 +1,564 @@
import type { ModerationState } from "./moderation-state-store";
import {
type VoidCandidateInterventions,
type VoidModerationCursor,
type VoidScheduledRuntime,
type VoidSelfProfile,
type VoidSpeechReceipts,
type VoidThoughtMemory,
voidCandidateInterventionsSchema,
voidModerationCursorSchema,
voidScheduledRuntimeSchema,
voidSelfProfileSchema,
voidSpeechReceiptsSchema,
voidThoughtMemorySchema,
} from "./void-self-state-domain";
type JsonObject = Record<string, unknown>;
export interface VoidSelfStateTypedProjection {
selfProfile: VoidSelfProfile;
moderationCursor: VoidModerationCursor;
speechReceipts: VoidSpeechReceipts;
thoughtMemory: VoidThoughtMemory;
scheduledRuntime: VoidScheduledRuntime;
candidateInterventions: VoidCandidateInterventions;
}
export function projectModerationStateToTypedSelfState(
state: ModerationState,
options: { projectedAt?: 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");
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)),
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"),
},
updatedAt: projectedAt,
}),
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,
}),
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,
}),
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,
}),
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,
}),
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,
}),
};
}
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

@ -90,3 +90,4 @@
{"ts":"2026-05-16T07:50:00Z","type":"research","status":"ok","note":"Correction to the self-state rebuild target: CultCache is natively polymorphic, so the architecture should use one CultCache-backed state authority with typed document kinds and mutation operations, not separate physical stores per self-state type. The ownership split is by document contract, not storage cabinet."}
{"ts":"2026-05-16T08:06:04Z","type":"research","status":"ok","note":"Clarified the teardown target: most deterministic cleanup in the memory organ is recent compensator cruft caused by failed attempts to manually clean an exploded moderation state file. The rebuild should prevent bad state from entering through typed CultCache operations, delete compensating cleanup paths as boundaries improve, and rewrite sleep/distillation with a meaning-preservation contract so concrete claims/evidence/tensions survive compression instead of becoming generic abstraction sludge."}
{"ts":"2026-05-16T10:03:21Z","type":"implementation","status":"ok","note":"The typed private self-state boundary now exists as code in packages/core/src/void-self-state-domain.ts: one polymorphic CultCache registry names global document kinds for self profile, moderation cursor/open cases/repo cursor, speech receipts, thought memory/incubation, scheduled runtime, and candidate interventions, plus strict operation payload schemas. This is Commit 1 territory only; runtime still uses the old moderation state store until read-only projections and mutation application are built."}
{"ts":"2026-05-16T11:01:13Z","type":"implementation","status":"ok","note":"Read-only typed self-state projection now exists in packages/core/src/void-self-state-projection.ts. The direct self-state loader derives nap/reply-mode projection from typed scheduled-runtime and thought-memory documents while preserving the older rich prompt summary until the new document model explicitly owns those details. Template and temp CultCache smoke checks passed."}

View file

@ -149,4 +149,4 @@ rejected_paths:
current_status:
summary: VoidBot's ordinary bot/worker/provider/RAG/Postgres/Qdrant structure is still conceptually sound, but the moderation/mood/private-self-state foundation has become architectural Jenga. It currently depends on canonical MessagePack plus an editable JSON projection, broad passthrough schemas, legacy mirror fields, a giant memory-organ cleanup pass, and a prompt-owned scheduled runner. Much of the cleanup pass is recent compensator cruft from attempts to manually clean exploded state; it should not be dignified into permanent architecture.
next_action: The typed CultCache self-state document and operation vocabulary now exists in core. Next build read-only typed projections over the current canonical moderation state so direct replies and runners can consume the new boundary shape before any mutation path moves. After that, add a typed mutation CLI/service and move repo cursor/open-case/receipt/candidate/memory updates behind it. Delete JSON projection authority and legacy mirrors early instead of adding adapters around them. Redesign sleep/distillation around a meaning-preservation contract before trusting it to compress memory.
next_action: The typed CultCache self-state document vocabulary and read-only projection layer now exist in core, and direct reply nap/reply-mode projection is derived from typed scheduled-runtime/thought-memory views. Next add a typed mutation service/CLI for cursor, open cases, delivery receipts, repo cursor, candidates, sleep/speaking pressure, and distilled memory, then move repo cursor/open-case/receipt/candidate/memory updates behind it. Delete JSON projection authority and legacy mirrors early instead of adding adapters around them. Redesign sleep/distillation around a meaning-preservation contract before trusting it to compress memory.