Add canonical native Persona CultCache state

This commit is contained in:
Meta Vens 2026-07-16 03:24:10 +01:00
commit b916dd577e
13 changed files with 288 additions and 5 deletions

View file

@ -24,3 +24,5 @@ export * from "./void-self-state-loader";
export * from "./void-self-state-domain";
export * from "./void-self-state-projection";
export * from "./void-self-state-service";
export * from "./persona-state-domain";
export * from "./persona-state-service";

View file

@ -0,0 +1,90 @@
import { defineDocumentRegistry, defineDocumentType } from "cultcache-ts";
import { z } from "zod";
const text = z.string().trim().min(1);
const timestamp = text;
const status = z.enum(["draft", "active", "cooling", "crystallized", "resolved", "retired"]);
const target = z.object({
kind: z.enum(["person", "repo", "scene", "system", "room", "artifact", "concept", "relationship", "self", "community", "thread", "document", "runtime", "custom"]),
id: text,
label: text.optional(),
customKind: text.optional(),
}).strict().superRefine((value, context) => {
if (value.kind === "custom" && !value.customKind) context.addIssue({ code: z.ZodIssueCode.custom, message: "Custom targets require customKind.", path: ["customKind"] });
});
const extensions = z.record(z.unknown()).optional();
const anchoredThought = z.object({
id: text,
status,
target,
summary: text,
claim: text.optional(),
question: text.optional(),
tension: text,
actionImplication: text,
intensity: z.number().min(0).max(1).optional(),
valence: z.number().min(-1).max(1).optional(),
createdAt: timestamp,
updatedAt: timestamp,
retiredAt: timestamp.optional(),
tags: z.array(text).default([]),
extensions,
}).strict();
const traitVector = z.object({ mean: z.number().min(0).max(1), plasticity: z.number().min(0).max(1), currentActivation: z.number().min(0).max(1) }).strict();
const traitMap = z.record(text, traitVector);
const activationProfile = z.object({
underlyingOrganization: traitMap,
stableDispositions: traitMap,
behavioralDimensions: traitMap,
presentationStrategy: traitMap,
voiceStyle: traitMap,
situationalState: traitMap,
}).strict();
const socialBond = z.object({
id: text, status, subject: target, object: target,
relationshipKind: z.enum(["ally", "friend", "collaborator", "mentor", "ward", "rival", "audience", "community_member", "self_relation", "unknown", "custom"]),
customRelationshipKind: text.optional(), summary: text, trust: z.number().min(0).max(1), tension: z.number().min(0).max(1), intensity: z.number().min(0).max(1).optional(), lastEvidence: anchoredThought.optional(), updatedAt: timestamp, extensions,
}).strict();
const statusRead = z.object({
id: text, status, target, statusKind: z.enum(["attention", "authority", "risk", "trust", "need", "conflict", "mood", "opportunity", "uncertainty", "custom"]), customStatusKind: text.optional(), summary: text, confidence: z.number().min(0).max(1), intensity: z.number().min(0).max(1).optional(), valence: z.number().min(-1).max(1).optional(), lastEvidence: anchoredThought.optional(), updatedAt: timestamp, extensions,
}).strict();
const doctrineStance = z.object({
id: text, status, target, stanceKind: z.enum(["aligned", "tension", "rejected", "uncertain", "contextual", "custom"]), customStanceKind: text.optional(), principle: text, summary: text, actionImplication: text, intensity: z.number().min(0).max(1).optional(), updatedAt: timestamp, extensions,
}).strict();
const candidateAction = z.object({
id: text, status, actionType: z.enum(["speak", "draft", "ask", "propose", "inspect", "notify", "wait", "remember", "handoff", "render", "external_action", "custom"]), customActionType: text.optional(), readiness: z.enum(["draft", "ready", "blocked", "waiting", "expired"]), riskLevel: z.enum(["none", "low", "medium", "high", "severe", "unknown"]), target, deliveryTarget: target.optional(), summary: text, rationale: text.optional(), urgency: z.number().min(0).max(1).optional(), confidence: z.number().min(0).max(1).optional(), constraints: z.array(text).default([]), evidence: z.array(anchoredThought).default([]), createdAt: timestamp, updatedAt: timestamp, expiresAt: timestamp.optional(), extensions,
}).strict();
export const gamecultPersonaStateSchema = z.object({
schemaVersion: z.literal("gamecult.persona_state.v0"),
provenance: z.object({ sourceSystem: text, sourceDocumentId: text, sourceUpdatedAt: timestamp, exportedAt: timestamp, authority: z.enum(["canonical", "projection", "import"]) }).strict(),
personaId: text,
publicName: text,
publicDescription: z.string(),
presentation: z.object({ avatarUri: z.string().url().optional(), pronouns: text.optional(), voiceSummary: text, defaultRenderer: z.enum(["text", "chat", "avatar", "voice", "scene", "repo_persona", "custom"]).optional(), customRenderer: text.optional(), homeContext: target.optional(), jurisdiction: text.optional(), publicHandles: z.array(z.object({ system: text, handle: text, uri: z.string().url().optional() }).strict()).default([]) }).strict(),
privateNotes: z.array(text).default([]),
values: z.array(z.object({ id: text, label: text, priority: z.number().min(0).max(1), summary: z.string().optional() }).strict()).default([]),
activationProfile: activationProfile.optional(),
thoughtMemory: z.object({ shortTerm: z.array(anchoredThought).default([]), memories: z.array(anchoredThought).default([]), incubation: z.array(anchoredThought).default([]) }).strict(),
agencyPressure: z.object({ pressures: z.array(anchoredThought).default([]) }).strict(),
candidateActions: z.object({ actions: z.array(candidateAction).default([]) }).strict().optional(),
voidbotProjection: z.object({ candidateInterventions: z.array(candidateAction).default([]) }).strict().optional(),
affect: z.object({
needs: z.array(anchoredThought).default([]), socialBonds: z.array(socialBond).default([]), statusReads: z.array(statusRead).default([]),
moodDimensions: z.array(z.object({ name: text, value: z.number().min(0).max(1), source: z.string().optional(), updatedAt: timestamp }).strict()).default([]),
socialBiases: z.array(z.object({ name: text, value: z.number().min(0).max(1), summary: text, behavioralPull: text, updatedAt: timestamp }).strict()).default([]),
doctrineStances: z.array(doctrineStance).default([]),
}).strict(),
updatedAt: timestamp,
}).strict();
export type GamecultPersonaState = z.infer<typeof gamecultPersonaStateSchema>;
export const gamecultPersonaStateDocument = defineDocumentType({
type: "gamecult.persona_state.v0",
schemaName: "gamecult.persona_state.v0",
schema: gamecultPersonaStateSchema,
global: true,
});
export const gamecultPersonaStateDocumentRegistry = defineDocumentRegistry(gamecultPersonaStateDocument);

View file

@ -0,0 +1,101 @@
import { access, readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { CultCache, SingleFileMessagePackBackingStore } from "cultcache-ts";
import { gamecultPersonaStateDocument, gamecultPersonaStateDocumentRegistry, gamecultPersonaStateSchema, type GamecultPersonaState } from "./persona-state-domain";
export async function loadGamecultPersonaState(canonicalPath: string): Promise<GamecultPersonaState> {
const cache = createCache(resolve(canonicalPath));
await cache.pullAllBackingStores();
const state = cache.getGlobal(gamecultPersonaStateDocument);
if (!state) throw new Error(`CultCache Persona state is missing gamecult.persona_state.v0: ${resolve(canonicalPath)}`);
return state;
}
export async function inspectPersonaStateSurfaceKind(canonicalPath: string): Promise<"gamecult_persona" | "void_self_state" | "unknown"> {
const envelopes = await new SingleFileMessagePackBackingStore(resolve(canonicalPath)).pullAll();
const types = new Set(envelopes.map((entry) => entry.type));
if (types.has(gamecultPersonaStateDocument.type)) return "gamecult_persona";
if ([...types].some((type) => type.startsWith("void."))) return "void_self_state";
return "unknown";
}
export async function migrateCanonicalPortablePersonaState(input: { sourcePath: string; targetPath: string }): Promise<{ sourcePath: string; targetPath: string; personaId: string }> {
const sourcePath = resolve(input.sourcePath);
const targetPath = resolve(input.targetPath);
const state = await readCanonicalPortablePersonaState(sourcePath);
try {
await access(targetPath);
throw new Error(`Refusing to overwrite existing Persona state target: ${targetPath}`);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
const cache = createCache(targetPath);
await cache.putGlobal(gamecultPersonaStateDocument, state);
const verified = await loadGamecultPersonaState(targetPath);
if (verified.personaId !== state.personaId || verified.updatedAt !== state.updatedAt) throw new Error(`Persona state verification failed after writing ${targetPath}`);
return { sourcePath, targetPath, personaId: state.personaId };
}
export async function readCanonicalPortablePersonaState(sourcePathInput: string): Promise<GamecultPersonaState> {
const sourcePath = resolve(sourcePathInput);
const raw = JSON.parse(stripBom(await readFile(sourcePath, "utf8"))) as unknown;
const claimedAuthority = readClaimedAuthority(raw);
if (claimedAuthority !== "canonical") throw new Error(`Refusing to promote ${claimedAuthority ?? "unclaimed"} Persona state; only canonical portable state may migrate.`);
return gamecultPersonaStateSchema.parse(normalizeLegacyPortableState(raw));
}
function normalizeLegacyPortableState(raw: unknown): unknown {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return raw;
const root = structuredClone(raw) as Record<string, unknown>;
const affect = root.affect;
const thoughtMemory = root.thoughtMemory;
if (!affect || typeof affect !== "object" || Array.isArray(affect) || !("stressResponses" in affect)) return root;
if (!thoughtMemory || typeof thoughtMemory !== "object" || Array.isArray(thoughtMemory)) return root;
const legacy = (affect as Record<string, unknown>).stressResponses;
if (!Array.isArray(legacy)) return root;
const memories = Array.isArray((thoughtMemory as Record<string, unknown>).memories)
? (thoughtMemory as Record<string, unknown>).memories as unknown[]
: [];
for (const entry of legacy) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const stress = entry as Record<string, unknown>;
const id = typeof stress.id === "string" ? stress.id : undefined;
const summary = typeof stress.summary === "string" ? stress.summary : undefined;
const createdAt = typeof stress.createdAt === "string" ? stress.createdAt : undefined;
const updatedAt = typeof stress.updatedAt === "string" ? stress.updatedAt : createdAt;
if (!id || !summary || !createdAt || !updatedAt || memories.some((memory) => (memory as Record<string, unknown> | undefined)?.id === id)) continue;
memories.push({
id,
status: stress.status ?? "active",
target: { kind: "self", id: `persona:${String(root.personaId ?? "unknown")}`, label: root.publicName },
summary,
claim: typeof stress.trigger === "string" ? stress.trigger : undefined,
tension: typeof stress.cognitiveDegradation === "string" ? stress.cognitiveDegradation : summary,
actionImplication: typeof stress.recoveryPath === "string" ? stress.recoveryPath : "Preserve this legacy stress response as migration evidence.",
intensity: stress.intensity,
createdAt,
updatedAt,
tags: [...(Array.isArray(stress.tags) ? stress.tags : []), "migration:legacy-stress-response"],
extensions: { legacyStressResponse: stress },
});
}
(thoughtMemory as Record<string, unknown>).memories = memories;
delete (affect as Record<string, unknown>).stressResponses;
return root;
}
function readClaimedAuthority(raw: unknown): string | undefined {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
const provenance = (raw as Record<string, unknown>).provenance;
if (!provenance || typeof provenance !== "object" || Array.isArray(provenance)) return undefined;
const authority = (provenance as Record<string, unknown>).authority;
return typeof authority === "string" ? authority : undefined;
}
function createCache(path: string): CultCache {
return CultCache.builder().withRegistry(gamecultPersonaStateDocumentRegistry).withGenericStore(new SingleFileMessagePackBackingStore(path)).build();
}
function stripBom(value: string): string { return value.charCodeAt(0) === 0xfeff ? value.slice(1) : value; }