Add typed Face affect state

This commit is contained in:
Meta Vens 2026-05-21 00:02:33 +01:00
commit 326c3bf18e
16 changed files with 636 additions and 17 deletions

View file

@ -9,6 +9,7 @@ export const VOID_SELF_STATE_DOCUMENT_TYPES = {
scheduledRuntime: "void.scheduled_runtime",
agencyPressure: "void.agency_pressure",
candidateInterventions: "void.candidate_interventions",
faceAffect: "void.face_affect",
} as const;
const nonEmptyStringSchema = z.string().trim().min(1);
@ -224,6 +225,118 @@ const agencyPressureSchema = z.object({
}
});
const faceAffectNeedSchema = z.object({
needId: nonEmptyStringSchema,
kind: z.enum([
"substrate",
"attention",
"agency",
"recognition",
"social_contact",
"territory",
"rest",
"play",
"status",
]),
status: z.enum(["active", "cooling", "satisfied", "neglected", "retired"]),
target: thoughtTargetSchema,
summary: boundedTextSchema,
claim: z.string().trim().min(1).max(2000).optional(),
question: z.string().trim().min(1).max(2000).optional(),
tension: z.string().trim().min(1).max(2000),
actionImplication: z.string().trim().min(1).max(2000),
intensity: z.number().min(0).max(1).default(0.5),
valence: z.number().min(-1).max(1).default(0),
anchorRefs: z.array(anchorRefSchema).default([]),
evidenceRefs: z.array(evidenceRefSchema).default([]),
sourceMemoryIds: z.array(nonEmptyStringSchema).default([]),
lastSatisfiedAt: timestampSchema.optional(),
createdAt: timestampSchema,
updatedAt: timestampSchema,
retiredAt: timestampSchema.optional(),
tags: z.array(nonEmptyStringSchema).default([]),
}).strict().superRefine((need, context) => {
if (!need.claim && !need.question) {
context.addIssue({
code: z.ZodIssueCode.custom,
message: "Affect needs must preserve at least one claim or question.",
path: ["claim"],
});
}
const admitsMissingAnchor = need.tags.includes("anchor:missing") || need.tags.includes("evidence:missing");
if (need.anchorRefs.length === 0 && need.evidenceRefs.length === 0 && need.sourceMemoryIds.length === 0 && !admitsMissingAnchor) {
context.addIssue({
code: z.ZodIssueCode.custom,
message: "Affect needs must include anchor refs, source memory ids, or explicitly tag anchor:missing.",
path: ["anchorRefs"],
});
}
});
const faceSocialBondSchema = z.object({
bondId: nonEmptyStringSchema,
target: thoughtTargetSchema,
stance: z.enum([
"fondness",
"rivalry",
"trust",
"irritation",
"protectiveness",
"envy",
"respect",
"suspicion",
"attachment",
]),
status: z.enum(["active", "cooling", "resolved", "retired"]),
summary: boundedTextSchema,
claim: z.string().trim().min(1).max(2000),
tension: z.string().trim().min(1).max(2000),
actionImplication: z.string().trim().min(1).max(2000),
intensity: z.number().min(0).max(1).default(0.5),
anchorRefs: z.array(anchorRefSchema).default([]),
evidenceRefs: z.array(evidenceRefSchema).default([]),
createdAt: timestampSchema,
updatedAt: timestampSchema,
retiredAt: timestampSchema.optional(),
tags: z.array(nonEmptyStringSchema).default([]),
}).strict();
const faceStatusReadSchema = z.object({
readId: nonEmptyStringSchema,
target: thoughtTargetSchema,
status: z.enum([
"favored",
"neglected",
"pampered",
"bypassed",
"blocked",
"challenged",
"ignored",
"consulted",
"threatened",
"admired",
]),
summary: boundedTextSchema,
claim: z.string().trim().min(1).max(2000),
tension: z.string().trim().min(1).max(2000),
actionImplication: z.string().trim().min(1).max(2000),
intensity: z.number().min(0).max(1).default(0.5),
anchorRefs: z.array(anchorRefSchema).default([]),
evidenceRefs: z.array(evidenceRefSchema).default([]),
createdAt: timestampSchema,
updatedAt: timestampSchema,
retiredAt: timestampSchema.optional(),
tags: z.array(nonEmptyStringSchema).default([]),
}).strict();
const faceMoodDimensionSchema = z.object({
name: nonEmptyStringSchema,
value: z.number().min(0).max(1),
source: z.string().trim().min(1).max(240).optional(),
updatedAt: timestampSchema,
}).strict();
const selfProfileValueSchema = z.object({
id: nonEmptyStringSchema,
label: nonEmptyStringSchema,
@ -309,6 +422,15 @@ export const voidAgencyPressureSchema = z.object({
updatedAt: timestampSchema,
}).strict();
export const voidFaceAffectSchema = z.object({
schemaVersion: z.literal(1),
needs: z.array(faceAffectNeedSchema).default([]),
socialBonds: z.array(faceSocialBondSchema).default([]),
statusReads: z.array(faceStatusReadSchema).default([]),
moodDimensions: z.array(faceMoodDimensionSchema).default([]),
updatedAt: timestampSchema,
}).strict();
export const voidSelfProfileDocument = defineDocumentType({
type: VOID_SELF_STATE_DOCUMENT_TYPES.selfProfile,
schema: voidSelfProfileSchema,
@ -351,6 +473,12 @@ export const voidCandidateInterventionsDocument = defineDocumentType({
global: true,
});
export const voidFaceAffectDocument = defineDocumentType({
type: VOID_SELF_STATE_DOCUMENT_TYPES.faceAffect,
schema: voidFaceAffectSchema,
global: true,
});
export const voidSelfStateDocumentRegistry = defineDocumentRegistry(
voidSelfProfileDocument,
voidModerationCursorDocument,
@ -359,6 +487,7 @@ export const voidSelfStateDocumentRegistry = defineDocumentRegistry(
voidScheduledRuntimeDocument,
voidAgencyPressureDocument,
voidCandidateInterventionsDocument,
voidFaceAffectDocument,
);
export const voidSelfStateOperationSchema = z.discriminatedUnion("operation", [
@ -455,6 +584,41 @@ export const voidSelfStateOperationSchema = z.discriminatedUnion("operation", [
retiredAt: timestampSchema,
reason: z.string().trim().min(1).max(1000),
}).strict(),
z.object({
operation: z.literal("upsert_affect_need"),
need: faceAffectNeedSchema,
}).strict(),
z.object({
operation: z.literal("retire_affect_need"),
needId: nonEmptyStringSchema,
retiredAt: timestampSchema,
reason: z.string().trim().min(1).max(1000),
}).strict(),
z.object({
operation: z.literal("upsert_social_bond"),
bond: faceSocialBondSchema,
}).strict(),
z.object({
operation: z.literal("retire_social_bond"),
bondId: nonEmptyStringSchema,
retiredAt: timestampSchema,
reason: z.string().trim().min(1).max(1000),
}).strict(),
z.object({
operation: z.literal("upsert_status_read"),
read: faceStatusReadSchema,
}).strict(),
z.object({
operation: z.literal("retire_status_read"),
readId: nonEmptyStringSchema,
retiredAt: timestampSchema,
reason: z.string().trim().min(1).max(1000),
}).strict(),
z.object({
operation: z.literal("update_mood_dimensions"),
dimensions: z.array(faceMoodDimensionSchema).min(1),
updatedAt: timestampSchema,
}).strict(),
z.object({
operation: z.literal("update_sleep_cycle"),
sleepCycle: voidScheduledRuntimeSchema.shape.sleepCycle,
@ -486,4 +650,5 @@ export type VoidThoughtMemory = z.infer<typeof voidThoughtMemorySchema>;
export type VoidScheduledRuntime = z.infer<typeof voidScheduledRuntimeSchema>;
export type VoidAgencyPressure = z.infer<typeof voidAgencyPressureSchema>;
export type VoidCandidateInterventions = z.infer<typeof voidCandidateInterventionsSchema>;
export type VoidFaceAffect = z.infer<typeof voidFaceAffectSchema>;
export type VoidSelfStateOperation = z.infer<typeof voidSelfStateOperationSchema>;

View file

@ -6,6 +6,7 @@ import {
import {
type VoidCandidateInterventions,
type VoidFaceAffect,
type VoidAgencyPressure,
type VoidModerationCursor,
type VoidScheduledRuntime,
@ -13,6 +14,7 @@ import {
type VoidSpeechReceipts,
type VoidThoughtMemory,
voidCandidateInterventionsSchema,
voidFaceAffectSchema,
voidAgencyPressureSchema,
voidModerationCursorSchema,
voidScheduledRuntimeSchema,
@ -29,6 +31,7 @@ export interface VoidSelfStateTypedProjection {
scheduledRuntime: VoidScheduledRuntime;
agencyPressure: VoidAgencyPressure;
candidateInterventions: VoidCandidateInterventions;
faceAffect: VoidFaceAffect;
}
export interface VoidSelfStateProjectionOptions {
@ -132,6 +135,14 @@ export function createEmptyVoidSelfState(
interventions: [],
updatedAt: createdAt,
}),
faceAffect: voidFaceAffectSchema.parse({
schemaVersion: 1,
needs: [],
socialBonds: [],
statusReads: [],
moodDimensions: [],
updatedAt: createdAt,
}),
};
}
@ -210,6 +221,7 @@ export function renderVoidSelfStateSummary(
.sort((left, right) => right.intensity - left.intensity)
.slice(0, 4)
.map((entry) => renderAgencyPressure(entry, identityName));
const affectLines = renderFaceAffectSummary(state.faceAffect, identityName);
return [
`- Identity: ${identityName}${identityDescription ? ` - ${identityDescription}` : ""}`,
@ -236,6 +248,7 @@ export function renderVoidSelfStateSummary(
agencyPressures.length > 0
? ["- Agency pressure:", ...agencyPressures].join("\n")
: "- Agency pressure: none active.",
affectLines,
interventions.length > 0
? [`- Things ${identityName} may say soon:`, ...interventions].join("\n")
: `- Things ${identityName} may say soon: none queued.`,
@ -265,6 +278,66 @@ function renderAgencyPressure(
return lines.join("\n");
}
function renderFaceAffectSummary(
affect: VoidFaceAffect,
identityName: string,
): string {
const needs = affect.needs
.filter((need) => ["active", "neglected"].includes(need.status))
.sort((left, right) => right.intensity - left.intensity)
.slice(0, 4);
const bonds = affect.socialBonds
.filter((bond) => bond.status === "active")
.sort((left, right) => right.intensity - left.intensity)
.slice(0, 4);
const reads = affect.statusReads
.filter((read) => !read.retiredAt)
.sort((left, right) => right.intensity - left.intensity)
.slice(0, 4);
const dimensions = affect.moodDimensions
.slice()
.sort((left, right) => right.value - left.value)
.slice(0, 8);
if (needs.length === 0 && bonds.length === 0 && reads.length === 0 && dimensions.length === 0) {
return `- What ${identityName} feels and wants: no explicit affect state yet.`;
}
return [
`- What ${identityName} feels and wants:`,
...needs.map((need) => {
const target = need.target.label ?? need.target.id;
return [
`- Need/${need.kind} for ${target} (${need.status}, ${need.intensity.toFixed(2)}): ${need.summary}`,
` ${identityName}'s claim: ${need.claim ?? need.question ?? "(unspoken)"}`,
` What rubs: ${need.tension}`,
` What it wants next: ${need.actionImplication}`,
].join("\n");
}),
...bonds.map((bond) => {
const target = bond.target.label ?? bond.target.id;
return [
`- Bond/${bond.stance} with ${target} (${bond.intensity.toFixed(2)}): ${bond.summary}`,
` ${identityName}'s read: ${bond.claim}`,
` How it should change behavior: ${bond.actionImplication}`,
].join("\n");
}),
...reads.map((read) => {
const target = read.target.label ?? read.target.id;
return [
`- Status read/${read.status} around ${target} (${read.intensity.toFixed(2)}): ${read.summary}`,
` ${identityName}'s read: ${read.claim}`,
` What it should do: ${read.actionImplication}`,
].join("\n");
}),
dimensions.length > 0
? `- Mood dimensions: ${dimensions.map((dimension) => `${dimension.name}=${dimension.value.toFixed(2)}`).join(", ")}`
: undefined,
]
.filter((line): line is string => typeof line === "string")
.join("\n");
}
export function buildVoidSelfStateProjection(
typedState: VoidSelfStateTypedProjection,
): VoidSelfStateContext["projection"] {
@ -291,6 +364,47 @@ export function buildVoidSelfStateProjection(
replyDirective: isNapping
? "You are in a scheduled nap. Reply in brief, low-effort, half-dreaming mutters instead of doing full attentive service-work."
: undefined,
affect: {
needs: typedState.faceAffect.needs
.filter((need) => ["active", "neglected"].includes(need.status))
.slice(0, 8)
.map((need) => ({
id: need.needId,
kind: need.kind,
status: need.status,
target: need.target,
summary: need.summary,
intensity: need.intensity,
valence: need.valence,
})),
socialBonds: typedState.faceAffect.socialBonds
.filter((bond) => bond.status === "active")
.slice(0, 8)
.map((bond) => ({
id: bond.bondId,
stance: bond.stance,
target: bond.target,
summary: bond.summary,
intensity: bond.intensity,
})),
statusReads: typedState.faceAffect.statusReads
.filter((read) => !read.retiredAt)
.slice(0, 8)
.map((read) => ({
id: read.readId,
status: read.status,
target: read.target,
summary: read.summary,
intensity: read.intensity,
})),
moodDimensions: typedState.faceAffect.moodDimensions
.slice(0, 16)
.map((dimension) => ({
name: dimension.name,
value: dimension.value,
source: dimension.source,
})),
},
};
}

View file

@ -4,6 +4,7 @@ import { CultCache, SingleFileMessagePackBackingStore } from "cultcache-ts";
import {
type VoidCandidateInterventions,
type VoidFaceAffect,
type VoidAgencyPressure,
type VoidModerationCursor,
type VoidScheduledRuntime,
@ -11,6 +12,7 @@ import {
type VoidSpeechReceipts,
type VoidThoughtMemory,
voidCandidateInterventionsDocument,
voidFaceAffectDocument,
voidAgencyPressureDocument,
voidModerationCursorDocument,
voidScheduledRuntimeDocument,
@ -63,7 +65,7 @@ export async function applyVoidSelfStateOperation(
return {
operation: operation.operation,
canonicalPath,
typedDocumentsWritten: 7,
typedDocumentsWritten: 8,
};
}
@ -81,7 +83,7 @@ export async function ensureVoidSelfStateIdentityProfile(
return {
operation: "ensure_identity_profile",
canonicalPath,
typedDocumentsWritten: 7,
typedDocumentsWritten: 8,
};
}
@ -98,7 +100,7 @@ export async function repairVoidSelfStateTypedDocuments(
return {
operation: "repair_typed_state",
canonicalPath,
typedDocumentsWritten: 7,
typedDocumentsWritten: 8,
};
}
@ -123,6 +125,7 @@ function readTypedStateOrEmpty(
agencyPressure: cache.getGlobal(voidAgencyPressureDocument) ?? empty.agencyPressure,
candidateInterventions:
cache.getGlobal(voidCandidateInterventionsDocument) ?? empty.candidateInterventions,
faceAffect: cache.getGlobal(voidFaceAffectDocument) ?? empty.faceAffect,
};
if (identity) {
repairSelfProfileIdentity(state, identity);
@ -144,6 +147,7 @@ async function writeTypedState(
await cache.putGlobal(voidScheduledRuntimeDocument, stripUndefined(state.scheduledRuntime));
await cache.putGlobal(voidAgencyPressureDocument, stripUndefined(state.agencyPressure));
await cache.putGlobal(voidCandidateInterventionsDocument, stripUndefined(state.candidateInterventions));
await cache.putGlobal(voidFaceAffectDocument, stripUndefined(state.faceAffect));
}
function repairSelfProfileIdentity(
@ -367,6 +371,45 @@ function applyTypedOperation(
case "retire_agency_pressure":
retireAgencyPressure(state.agencyPressure, operation);
return;
case "upsert_affect_need":
upsertBy(state.faceAffect.needs, operation.need, (entry) => entry.needId);
state.faceAffect.needs = state.faceAffect.needs
.sort((left, right) => right.intensity - left.intensity)
.slice(0, 24);
state.faceAffect.updatedAt = operation.need.updatedAt;
return;
case "retire_affect_need":
retireAffectNeed(state.faceAffect, operation);
return;
case "upsert_social_bond":
upsertBy(state.faceAffect.socialBonds, operation.bond, (entry) => entry.bondId);
state.faceAffect.socialBonds = state.faceAffect.socialBonds
.sort((left, right) => right.intensity - left.intensity)
.slice(0, 24);
state.faceAffect.updatedAt = operation.bond.updatedAt;
return;
case "retire_social_bond":
retireSocialBond(state.faceAffect, operation);
return;
case "upsert_status_read":
upsertBy(state.faceAffect.statusReads, operation.read, (entry) => entry.readId);
state.faceAffect.statusReads = state.faceAffect.statusReads
.sort((left, right) => right.intensity - left.intensity)
.slice(0, 24);
state.faceAffect.updatedAt = operation.read.updatedAt;
return;
case "retire_status_read":
retireStatusRead(state.faceAffect, operation);
return;
case "update_mood_dimensions":
for (const dimension of operation.dimensions) {
upsertBy(state.faceAffect.moodDimensions, dimension, (entry) => entry.name);
}
state.faceAffect.moodDimensions = state.faceAffect.moodDimensions
.sort((left, right) => right.value - left.value)
.slice(0, 32);
state.faceAffect.updatedAt = operation.updatedAt;
return;
case "update_sleep_cycle":
state.scheduledRuntime.sleepCycle = operation.sleepCycle;
state.scheduledRuntime.updatedAt = new Date().toISOString();
@ -580,6 +623,47 @@ function retireAgencyPressure(
agencyPressure.updatedAt = operation.retiredAt;
}
function retireAffectNeed(
faceAffect: VoidFaceAffect,
operation: Extract<VoidSelfStateOperation, { operation: "retire_affect_need" }>,
): void {
const need = faceAffect.needs.find((entry) => entry.needId === operation.needId);
if (need) {
need.status = "retired";
need.retiredAt = operation.retiredAt;
need.updatedAt = operation.retiredAt;
need.tags = Array.from(new Set([...need.tags, `retired:${operation.reason}`]));
}
faceAffect.updatedAt = operation.retiredAt;
}
function retireSocialBond(
faceAffect: VoidFaceAffect,
operation: Extract<VoidSelfStateOperation, { operation: "retire_social_bond" }>,
): void {
const bond = faceAffect.socialBonds.find((entry) => entry.bondId === operation.bondId);
if (bond) {
bond.status = "retired";
bond.retiredAt = operation.retiredAt;
bond.updatedAt = operation.retiredAt;
bond.tags = Array.from(new Set([...bond.tags, `retired:${operation.reason}`]));
}
faceAffect.updatedAt = operation.retiredAt;
}
function retireStatusRead(
faceAffect: VoidFaceAffect,
operation: Extract<VoidSelfStateOperation, { operation: "retire_status_read" }>,
): void {
const read = faceAffect.statusReads.find((entry) => entry.readId === operation.readId);
if (read) {
read.retiredAt = operation.retiredAt;
read.updatedAt = operation.retiredAt;
read.tags = Array.from(new Set([...read.tags, `retired:${operation.reason}`]));
}
faceAffect.updatedAt = operation.retiredAt;
}
function closeCasesForReceipt(
cursor: VoidModerationCursor,
receipt: VoidSpeechReceipts["recentReceipts"][number],