diff --git a/apps/persona-scheduler/src/persona-memory-projector.ts b/apps/persona-scheduler/src/persona-memory-projector.ts index 6aef944..d8d6d1d 100644 --- a/apps/persona-scheduler/src/persona-memory-projector.ts +++ b/apps/persona-scheduler/src/persona-memory-projector.ts @@ -1,4 +1,62 @@ import { loadPromptTemplate } from "@voidbot/shared"; +import type { VoidSelfStateTypedProjection } from "@voidbot/core"; + +export interface PersonaTypedStateSections { + opening: string[]; + needs: string[]; + bonds: string[]; + statusMoodMemory: string[]; +} + +export function renderPersonaTypedStateSections(input: { + identityName: string; + state: VoidSelfStateTypedProjection; +}): PersonaTypedStateSections { + const { identityName: name, state } = input; + const opening: string[] = []; + const selfTexture = [ + ...state.selfProfile.privateNotes.map(projectPrivateNote), + ...[...state.selfProfile.values].sort((left, right) => right.priority - left.priority).map((value) => value.summary || value.label), + ].map(cleanSentence).filter(Boolean).slice(0, 18); + if (selfTexture.length > 0) opening.push(`Right now, ${name} is carrying this close to the skin: ${joinNarrative(selfTexture)}.`); + const activation = renderActivation(state.selfProfile.activationProfile); + if (activation) opening.push(activation); + const runtime = renderRuntime(name, state); + if (runtime) opening.push(runtime); + + const needs = [...state.faceAffect.needs].filter((entry) => entry.status !== "retired").sort(sortAffect); + const bonds = [...state.faceAffect.socialBonds].filter((entry) => entry.status !== "retired").sort(sortAffect); + const statusReads = [...state.faceAffect.statusReads].filter((entry) => !entry.retiredAt).sort(sortAffect); + const mood = [...state.faceAffect.moodDimensions].sort((left, right) => right.value - left.value); + const durable = [...state.thoughtMemory.memories].filter((entry) => !entry.retiredAt).slice(-12).reverse(); + const shortTerm = [...state.thoughtMemory.shortTerm].filter((entry) => !entry.retiredAt).slice(-12).reverse(); + return { + opening, + needs: needs.length === 0 ? [] : [[`${name}'s explicit needs and frictions:`, ...needs.map((need) => [ + `- ${need.kind} need toward ${targetLabel(need.target)} [${need.status}, intensity ${need.intensity.toFixed(2)}, valence ${need.valence.toFixed(2)}]: ${sentence(need.summary)}`, + need.claim ? `Claim: ${sentence(need.claim)}` : need.question ? `Question: ${sentence(need.question)}` : "", + `Tension: ${sentence(need.tension)}`, + `Behavioral pull: ${sentence(need.actionImplication)}`, + ].filter(Boolean).join(" "))].join("\n")], + bonds: bonds.length === 0 ? [] : [["The social map has teeth:", ...bonds.map((bond) => [ + `- ${targetLabel(bond.target)} draws ${bond.stance} [${bond.status}, intensity ${bond.intensity.toFixed(2)}]: ${sentence(bond.summary)}`, + `Read: ${sentence(bond.claim)}`, + `Tension: ${sentence(bond.tension)}`, + `Behavioral pull: ${sentence(bond.actionImplication)}`, + ].join(" "))].join("\n")], + statusMoodMemory: [ + statusReads.length === 0 ? undefined : ["Status in the swarm is part of the weather:", ...statusReads.map((read) => [ + `- Around ${targetLabel(read.target)}, ${name} feels ${read.status} [intensity ${read.intensity.toFixed(2)}]: ${sentence(read.summary)}`, + `Read: ${sentence(read.claim)}`, + `Tension: ${sentence(read.tension)}`, + `Behavioral pull: ${sentence(read.actionImplication)}`, + ].join(" "))].join("\n"), + mood.length === 0 ? undefined : ["Mood dimensions currently bending the turn:", ...mood.map((dimension) => `- ${dimension.name}=${dimension.value.toFixed(2)}${dimension.source ? ` from ${cleanSentence(dimension.source)}` : ""}`)].join("\n"), + durable.length === 0 ? undefined : ["Durable memories that should still bias judgment:", ...durable.map((memory) => renderMemory(name, memory))].join("\n"), + shortTerm.length === 0 ? undefined : ["Short-term residue waiting to settle:", ...shortTerm.map((memory) => renderMemory(name, memory))].join("\n"), + ].filter((section): section is string => Boolean(section)), + }; +} export async function projectPersonaMemorySurface(input: { identityId: string; @@ -33,3 +91,34 @@ export function validatePersonaMemorySurface(surface: string): string { } return surface; } + +function sortAffect(left: { status?: string; intensity?: number }, right: { status?: string; intensity?: number }): number { + const rank = (status?: string): number => ["neglected", "ready_to_act"].includes(status ?? "") ? 0 : ["active", "challenged"].includes(status ?? "") ? 1 : status === "cooling" ? 2 : ["satisfied", "resolved"].includes(status ?? "") ? 3 : 4; + return rank(left.status) - rank(right.status) || (right.intensity ?? 0) - (left.intensity ?? 0); +} +function renderActivation(profile: VoidSelfStateTypedProjection["selfProfile"]["activationProfile"]): string | undefined { + const sections = Object.entries(profile).map(([section, values]) => { + const entries = Object.entries(values).sort(([, left], [, right]) => vectorWeight(right) - vectorWeight(left)).map(([key, value]) => `${key}=${vectorWeight(value).toFixed(2)}${vectorNote(value) ? ` (${cleanSentence(vectorNote(value))})` : ""}`); + return entries.length > 0 ? `- ${section}: ${entries.join("; ")}` : undefined; + }).filter((entry): entry is string => Boolean(entry)); + return sections.length > 0 ? ["Activation profile that should color behavior:", ...sections].join("\n") : undefined; +} +function renderRuntime(name: string, state: VoidSelfStateTypedProjection): string { + const lines: string[] = []; + const sleep = state.scheduledRuntime.sleepCycle; + if (sleep.isNapping || sleep.activeDreamThemes.length > 0) lines.push(`${name}'s rest state: ${sleep.isNapping ? "currently in a sleep/low-output phase" : "awake but carrying dream residue"}${sleep.activeDreamThemes.length > 0 ? ` around ${joinNarrative(sleep.activeDreamThemes.map(cleanSentence))}` : ""}.`); + const speaking = state.scheduledRuntime.speakingPressure; + const parts = [`need to speak ${speaking.needToSpeak.toFixed(2)}`, typeof speaking.confessionPressure === "number" ? `confession ${speaking.confessionPressure.toFixed(2)}` : "", typeof speaking.noveltyPressure === "number" ? `novelty ${speaking.noveltyPressure.toFixed(2)}` : "", typeof speaking.recentSpeechDamping === "number" ? `recent-speech damping ${speaking.recentSpeechDamping.toFixed(2)}` : ""].filter(Boolean); + lines.push(`Speaking pressure: ${parts.join(", ")}. Treat this as appetite/restraint, not an order.`); + if (state.scheduledRuntime.lastRuns.length > 0) lines.push(`Recent internal passes: ${state.scheduledRuntime.lastRuns.slice(-4).map((run) => cleanSentence(run.summary)).join(" | ")}`); + return lines.join("\n"); +} +function renderMemory(name: string, memory: VoidSelfStateTypedProjection["thoughtMemory"]["memories"][number]): string { return [`- ${memory.kind} about ${targetLabel(memory.target)}: ${sentence(memory.summary)}`, memory.claim ? `Claim: ${sentence(memory.claim)}` : "", memory.question ? `Question: ${sentence(memory.question)}` : "", memory.tension ? `Tension: ${sentence(memory.tension)}` : "", memory.actionImplication ? `Behavioral pull for ${name}: ${sentence(memory.actionImplication)}` : ""].filter(Boolean).join(" "); } +function targetLabel(target: { label?: string; id?: string; kind?: string } | undefined): string { return target?.label ?? target?.id ?? target?.kind ?? "an unnamed target"; } +function vectorWeight(value: unknown): number { if (!record(value)) return 0; const candidate = [value.weight, value.current_activation, value.currentActivation, value.mean].find((entry) => typeof entry === "number" && Number.isFinite(entry)); return typeof candidate === "number" ? candidate : 0; } +function vectorNote(value: unknown): string | undefined { return record(value) && typeof value.note === "string" ? value.note : undefined; } +function projectPrivateNote(note: string): string { return note.replace(/\bdo not prompt (?:her|him|them|it|[A-Z][A-Za-z0-9_-]*) as\b/gi, "she refuses to be treated as").replace(/\bdo not prompt\b/gi, "do not treat").replace(/\bprompt (?:her|him|them|it)\b/gi, "treat them").replace(/\bprompt [A-Z][A-Za-z0-9_-]*\b/g, "treat them"); } +function cleanSentence(value: string | undefined): string { return (value ?? "").replace(/\s*\|\s*/g, " ").replace(/\bFace of\s+[A-Za-z0-9_-]+\b/gi, "").replace(/\bgrants:\s*[^.]+/gi, "").replace(/\bjurisdictions:\s*[^.]+/gi, "").replace(/\brepo=[^\s]+/gi, "").replace(/\bpath=[^\s]+/gi, "").replace(/\bvoid\.face_[A-Za-z0-9_.-]+/gi, "").replace(/\s{2,}/g, " ").trim().replace(/[.;:,]+$/g, ""); } +function sentence(value: string | undefined): string { const cleaned = cleanSentence(value); return !cleaned ? "" : /[.!?]$/.test(cleaned) ? cleaned : `${cleaned}.`; } +function joinNarrative(items: string[]): string { return items.length <= 1 ? items[0] ?? "" : items.length === 2 ? `${items[0]}, and ${items[1]}` : `${items.slice(0, -1).join(", ")}, and ${items.at(-1)}`; } +function record(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 128a877..bc6f82f 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -152,6 +152,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - Persona Body/Mind acquisition is isolated in `persona-state-source.ts`. It resolves the registered `.cc` surface, loads typed state once for a scheduler pulse, and projects current sleep facts at an explicit wall-clock time. It cannot create a missing state file, update sleep cycles or speaking pressure, select work, or queue turns. The old heartbeat-shell physiology writer and its pulse-driven speaking-pressure heuristic were deleted; `initiative-engine.ts` remains the only owner of rest eligibility. - Semantic Persona-memory recall is isolated in `persona-memory-context-source.ts`. It requires an existing `PersonaStateObservation`, rebuilds only that Persona's derived vector partition, searches it against current/nearby room evidence, and returns structured hits or an explicit unavailable result. It cannot reopen canonical `.cc` state, mutate Persona Mind, or render prompt doctrine. The heartbeat shell now only turns the typed observation into character-facing text. - Persona memory projection policy is isolated in `persona-memory-projector.ts`. It owns the deterministic/model choice, projector prompt template, minimum model-output invariant, and schema/path leak rejection through an injected text-model port. Repo Faces and typed native Personas use the same boundary. The large deterministic state-packet renderer is still in the heartbeat shell and is the next extraction target. +- The pure typed-state core of that packet now also lives in `persona-memory-projector.ts`: private identity texture, activation vectors, runtime/rest/speaking pressure, needs, bonds, status reads, mood dimensions, and durable/short-term memories. The shell still owns agency/incubation/candidate/receipt rendering and the ordering of externally acquired social, room, clarity, maintenance, and curiosity facts; those are the remaining packet-builder debris. - Home-repo activity acquisition is isolated in `repo-activity-source.ts`. It owns source-repo/cursor resolution and the bounded read-only exporter invocation, returning typed observations that prompt composition renders without subprocess or JSON-parsing authority. - Deployment authority detail: Idunn executes `/srv/odin/deploy-manifests/voidbot`; `/usr/local/sbin/deploy-voidbot` is only the identical inspection/recovery copy. Install both from `gamecult-ops/scripts/deploy-voidbot.sh`. `/srv/build/VoidBot/.git` and `/srv/build/cultcache-ts/.git` must remain wholly `idunn`-owned because lazy partial-clone reads can fetch objects; root owns releases and service promotion, never build-repo Git state. - Dynamic heat is live as derived semantic response pressure. `semantic-pressure-source.ts` batches canonical Face affinity cards and recent permitted-channel human-message embeddings through the existing RAG embedder, applies recency decay/noisy-OR aggregation, and returns bounded projections for at most three scheduler-eligible Faces. It does not write scheduler state. `initiative-engine.ts` alone commits inspectable evidence, `dynamicHeat`, one-time semantic interrupt receipts, and readiness changes. Direct mentions remain obligations, and model/Discord failures fail cool without bypassing rest, active jobs, or scheduler capacity. diff --git a/notes/voidbot-current-system-map.md b/notes/voidbot-current-system-map.md index 2d0f5dc..67d0c2d 100644 --- a/notes/voidbot-current-system-map.md +++ b/notes/voidbot-current-system-map.md @@ -182,7 +182,7 @@ VoidBot runs on Yggdrasil. Idunn owns deployment and consumes upstream repositor - Repo Face proposal/article PRs, PR comments, registered-identity Discord posts, and r/GameCultOrg Reddit thread posts now cross through parent-owned action blocks before Bifrost bridge commands. Bylined essays use the Interpreter-owned `ARTICLE` block: the Face writes naturally, the Interpreter extracts structured title/description/author/date/tags/path/body fields, and deterministic worker code renders/validates YAML frontmatter before calling `BIFROST_ROOT/tools/bifrost-bridge.mjs` for a draft PR and persona announcement. Subreddit threads use the Interpreter-owned `REDDIT THREAD` block: the Face writes a public title/body/share line, and deterministic worker code calls Bifrost `reddit-post` with Persona flair. The old `VOIDBOT_REPO_IDENTITY_ARTICLE` JSON sentinel is cut. Proposal PR and PR-comment sentinels still exist as compatibility rails. This is not merely helper placement: Bifrost's original governance/labor platform role makes it the owner of governed public crossings for GameCult work, including GitHub, r/GameCultOrg Reddit transport/thread access, Discord-native work/member/swarm interactions, dispatch receipts, CultNet/CultCache intake, and future collaboration interfaces. Heimdall is the OAuth/account/capability gate; Bifrost is the bridge/request/routing/receipt authority. VoidBot still owns room/thread cognition, moderation judgment, archive/source retrieval, and Face personality. - Repo Face turns now receive a Bifrost governance digest from `BIFROST_ROOT/tools/governance-threads.mjs digest --repo --agent ` alongside recent Discord context. Bifrost typed CultCache topics/comments are the canonical home for feature requests, Face opinions, missing questions, approvals, and dispatch receipts; Discord is a mirror/evidence source. When `BIFROST_DISCORD_CHANNEL_ID` is configured for `#bifrost`, repo Face Discord context ignores mirrored bot chatter there because the authoritative activity arrives through the Bifrost digest. Human `#bifrost` messages should only become governance comments after Bifrost/Heimdall can link the Discord id to a registered actor. Repo-local asks that would send a human or Codex to add/fix/name/scaffold/document/test/investigate/implement belong on Bifrost with enough room/repo context for a claimed Codex turn; a Face may still speak characterfully in Aquarium, but not as the only dispatch surface. Legacy `UPDATE REQUEST` packets are parsed only as compatibility input and reconciled into Bifrost topics instead of immediate transport enqueue. Local `#bifrost` is channel `1506760343836430376`; work proposals, governance mirrors, and Bifrost dispatch receipts should go there, while Aquarium remains the casual/social swarm room. - Repo character turns now have a state-projector plus turn-Interpreter shape. The state-in boundary is `prompts/repo-face-state-projector.prompt.md`: typed state and identity material are translated into lived character prose before the child sees it. The state projector must surface values, drives, wounds, fascinations, aesthetic taste, dignity, mood, needs, social reads, bonds, agency pressure, and the personality-specific meaning of sparse or dense social topology when the state contains those facts. The deterministic state packet feeding that projector is intentionally verbose and parent-facing: it exposes private notes, values, activation vectors, runtime rest/speaking pressure, affect needs, bonds, status reads, mood dimensions, durable memories, short-term residue, agency pressures, incubating thoughts, candidate speech pressure, recent speech residue, social graph facts, room weather, and semantic curiosity graph attractors so every included variable can appear directly or bend behavior. The curiosity graph is built by seeding history/source vector retrieval from current room context, nearby channels, typed Face state, and home-jurisdiction identity, then decoding retrieved chunks into weighted attractor clusters with prominence, saturation, novelty, density, jurisdiction fit, suggested motion, and evidence labels. The projector owns turning those neutral facts into lived curiosity, boredom, fatigue, territorial pull, underexplored intrigue, or a closing/pivot impulse; deterministic code must not decide the feeling. Deterministic code may also attach neutral graph facts such as mapped people and unmapped registered peers to the projector packet, but it must not decide whether that feels like anxiety, territorial scouting, or nothing. Deterministic code attaches recent read-only home-repo activity before chat, using the Face's own state path as the repo-activity cursor source, so current implementation motion is visible as body context. Current-room and nearby-channel logs no longer cross a model conversation projector; deterministic code attaches raw oldest-to-newest transcript evidence with explicit recency/correction rules so the Face can notice human reframes directly. Deterministic code also attaches a social-affordance surface that matches active typed person-bonds/status reads to recent raw messages from that person, so relationship state arrives as a live hook rather than private decorative lore. Deterministic code still owns full prompt assembly and inspection through `scripts/run-repo-face-heartbeats.ts --assemble-prompt `; that path composes stable doctrine, allowed rooms, research/archive capability guidance, Bifrost digest, projected memory/affect prose, home-repo activity, live social affordances, and raw conversation evidence into the exact child prompt. It must not invent personality, mood, affect, or social memory from typed state. Situational obligations such as direct-call priority or first-public-introduction duty are emitted only when the scheduler packet proves they apply, not as standing prompt law. The child character writes a natural in-character turn on full `gpt-5.4` and may describe desired speech, repo/article proposals, social reads, needs, mood shifts, or memory-worthy thoughts without emitting action DSL blocks. The cheaper Spark/Mini parent Interpreter decides route/retry/drop and translates warranted effects into structured `STATE NOTE` and `SAY` blocks for the worker while governance dispatch remains paused. `STATE NOTE` blocks become typed short-term memory, affect needs, social bonds, status reads, mood dimensions, or agency pressure. The worker still accepts legacy compact JSON sentinels and legacy `UPDATE REQUEST` blocks for compatibility, but the live prompt path keeps transport and state syntax out of the character's roleplay surface. -- `apps/persona-scheduler` is the resident daemon organ that owns the serialized Persona wall-clock pulse on Yggdrasil. It invokes the remaining turn orchestrator without overlap and remains alive between pulses. `apps/persona-scheduler/src/initiative-engine.ts` owns the pure scheduling state machine: participant reconciliation, deterministic base speed/bias/threshold derivation, operator heat/speed projection, semantic-pressure commits, wall-clock advancement, active-turn freeze/completion recovery, queue-success/failure/dry-run commits, stale rescheduling, pending-mention priority, rest/idle eligibility, and ready ordering. Explicit blocked/withdrawn status, active load, semantic receipts, and initiative position survive reconciliation; new Faces without a usable mouth fail closed. `apps/persona-scheduler/src/state-store.ts` owns scheduler persistence and legacy migration. It stores one typed `voidbot.persona_scheduler_state` record in `repo-face-heartbeats.cc`, migrates the former JSON document once with a `storage_migrated` witness, rejects malformed CultCache instead of replacing it, and writes JSON only as a derived dashboard/debug projection. `packages/core/src/repo-face-heartbeat-queue.ts` resolves both legacy `.json` configuration and current `.cc` configuration to the same canonical path; the Discord bot publishes one immutable `voidbot.persona_attention_command` CultCache inbox document per addressed message. The scheduler store ingests and deduplicates those commands, persists them as pending attention, then acknowledges inbox files only after the durable commit; a crash before acknowledgement replays safely. `apps/persona-scheduler/src/active-turn-source.ts` owns the Postgres/legacy-lock liveness adapter. It recognizes only Persona turn request IDs, applies the bounded stale threshold, marks dead queue claims failed, and returns active/stale witnesses; it never writes scheduler state. `apps/persona-scheduler/src/persona-state-source.ts` owns read-only typed Persona-state acquisition and present-time physiology projection. It reports typed mind plus rest facts without creating missing state or writing sleep/speaking-pressure state; the initiative engine alone applies rest eligibility. `apps/persona-scheduler/src/persona-memory-context-source.ts` owns the derived vector refresh and semantic recall query for one supplied typed Mind observation. It returns typed hits/unavailability and cannot reacquire canonical state, render prompt prose, or queue work. `apps/persona-scheduler/src/persona-memory-projector.ts` owns deterministic/model projection policy, its prompt template, output sufficiency, and leak rejection through an injected text-model port. It cannot acquire state, retrieve vectors, or queue work. `apps/persona-scheduler/src/discord-activity-source.ts` owns neutral Discord activity acquisition: it deduplicates explicit watched channels, excludes bot traffic, reports raw human messages, and derives idle-cooling times from scheduler history without writing state or selecting work. `apps/persona-scheduler/src/semantic-pressure-source.ts` owns embedding-backed affinity observation and returns bounded projections for eligible Personas and permitted channels. It cannot mutate initiative; `initiative-engine.ts` alone applies pressure, dynamic heat, interrupt readiness, dedupe receipts, and transition history. `apps/persona-scheduler/src/turn-context-source.ts` owns current-room and nearby-channel Discord evidence plus the bounded image-attachment cache. It returns chronological source messages and explicit snapshot failure witnesses; it has no access to Persona state, prompt composition, or the job queue. `scripts/run-repo-face-heartbeats.ts` projects the identity registry into neutral participant specs and affinity candidates, still builds the deterministic Persona state packet, renders typed source observations, and invokes external queue actuators pending further extraction. External adapters report facts; only the initiative engine mutates load, counters, recovery position, pressure, and queue-transition history. Repo Faces and native Personas queue ordinary `repo-face-rumination` jobs through the canonical job queue. Built-in Void participates only when its separate moderation heartbeat organ is enabled; the hosted scheduler does not launch Windows PowerShell. +- `apps/persona-scheduler` is the resident daemon organ that owns the serialized Persona wall-clock pulse on Yggdrasil. It invokes the remaining turn orchestrator without overlap and remains alive between pulses. `apps/persona-scheduler/src/initiative-engine.ts` owns the pure scheduling state machine: participant reconciliation, deterministic base speed/bias/threshold derivation, operator heat/speed projection, semantic-pressure commits, wall-clock advancement, active-turn freeze/completion recovery, queue-success/failure/dry-run commits, stale rescheduling, pending-mention priority, rest/idle eligibility, and ready ordering. Explicit blocked/withdrawn status, active load, semantic receipts, and initiative position survive reconciliation; new Faces without a usable mouth fail closed. `apps/persona-scheduler/src/state-store.ts` owns scheduler persistence and legacy migration. It stores one typed `voidbot.persona_scheduler_state` record in `repo-face-heartbeats.cc`, migrates the former JSON document once with a `storage_migrated` witness, rejects malformed CultCache instead of replacing it, and writes JSON only as a derived dashboard/debug projection. `packages/core/src/repo-face-heartbeat-queue.ts` resolves both legacy `.json` configuration and current `.cc` configuration to the same canonical path; the Discord bot publishes one immutable `voidbot.persona_attention_command` CultCache inbox document per addressed message. The scheduler store ingests and deduplicates those commands, persists them as pending attention, then acknowledges inbox files only after the durable commit; a crash before acknowledgement replays safely. `apps/persona-scheduler/src/active-turn-source.ts` owns the Postgres/legacy-lock liveness adapter. It recognizes only Persona turn request IDs, applies the bounded stale threshold, marks dead queue claims failed, and returns active/stale witnesses; it never writes scheduler state. `apps/persona-scheduler/src/persona-state-source.ts` owns read-only typed Persona-state acquisition and present-time physiology projection. It reports typed mind plus rest facts without creating missing state or writing sleep/speaking-pressure state; the initiative engine alone applies rest eligibility. `apps/persona-scheduler/src/persona-memory-context-source.ts` owns the derived vector refresh and semantic recall query for one supplied typed Mind observation. It returns typed hits/unavailability and cannot reacquire canonical state, render prompt prose, or queue work. `apps/persona-scheduler/src/persona-memory-projector.ts` owns deterministic/model projection policy, its prompt template, output sufficiency, leak rejection, and the pure typed-state core sections: identity texture, activation/runtime pressure, needs, bonds, status, mood, and durable/short-term memory. It cannot acquire state, retrieve vectors, or queue work. `apps/persona-scheduler/src/discord-activity-source.ts` owns neutral Discord activity acquisition: it deduplicates explicit watched channels, excludes bot traffic, reports raw human messages, and derives idle-cooling times from scheduler history without writing state or selecting work. `apps/persona-scheduler/src/semantic-pressure-source.ts` owns embedding-backed affinity observation and returns bounded projections for eligible Personas and permitted channels. It cannot mutate initiative; `initiative-engine.ts` alone applies pressure, dynamic heat, interrupt readiness, dedupe receipts, and transition history. `apps/persona-scheduler/src/turn-context-source.ts` owns current-room and nearby-channel Discord evidence plus the bounded image-attachment cache. It returns chronological source messages and explicit snapshot failure witnesses; it has no access to Persona state, prompt composition, or the job queue. `scripts/run-repo-face-heartbeats.ts` projects the identity registry into neutral participant specs and affinity candidates, still composes externally acquired facts with the remaining agency/incubation/candidate/receipt sections, and invokes external queue actuators pending further extraction. External adapters report facts; only the initiative engine mutates load, counters, recovery position, pressure, and queue-transition history. Repo Faces and native Personas queue ordinary `repo-face-rumination` jobs through the canonical job queue. Built-in Void participates only when its separate moderation heartbeat organ is enabled; the hosted scheduler does not launch Windows PowerShell. - `apps/persona-scheduler/src/bifrost-governance-source.ts` owns the remaining Bifrost governance digest subprocess contract. It supplies the CLI path, arguments, timeout, JSON parsing, and typed command/parse failure topics; Persona prompt composition receives a `BifrostGovernanceDigest` and cannot invoke Bifrost directly. - The scheduler state has one write authority. `initiative-engine.ts` commits participant reconciliation, operator controls, pause/disabled skips, stale-turn recovery witnesses, semantic pressure, pending-attention consumption, queue outcomes, and tick finalization. `run-repo-face-heartbeats.ts` contains no direct participant/state assignment or history append; its sources and actuators return facts to engine commits. - `apps/persona-scheduler/src/turn-actuator.ts` is the worker-queue output port. Given a completed prompt, output channel, evidence fields, provider, identity, timestamp, and narrow `createJob` capability, it builds the canonical worker actor/guild `ContextBundle`, creates one approved `repo-face-rumination` job, and returns `{created, activeJobId, requestMessageId}`. It cannot choose a Persona, mutate scheduler state, or compose prompt content. The orchestration shell no longer knows `ContextBuilder`, job approval defaults, worker command names, or `createJob` mechanics. diff --git a/scripts/run-repo-face-heartbeats.ts b/scripts/run-repo-face-heartbeats.ts index 64445c5..d849d12 100644 --- a/scripts/run-repo-face-heartbeats.ts +++ b/scripts/run-repo-face-heartbeats.ts @@ -62,7 +62,7 @@ import { readPersonaMemoryRecall, type PersonaMemoryRecallObservation, } from "../apps/persona-scheduler/dist/persona-memory-context-source.js"; -import { projectPersonaMemorySurface } from "../apps/persona-scheduler/dist/persona-memory-projector.js"; +import { projectPersonaMemorySurface, renderPersonaTypedStateSections, validatePersonaMemorySurface } from "../apps/persona-scheduler/dist/persona-memory-projector.js"; import { readDiscordActivitySnapshot, type IdleCoolingSnapshot, @@ -1121,32 +1121,12 @@ function renderRepoFaceStatePacket( ): string { const name = identity.displayName; const lines: string[] = []; - const profile = state.selfProfile; - const privateNotes = profile.privateNotes; - const values = [...profile.values] - .sort((left, right) => right.priority - left.priority); const needs = [...state.faceAffect.needs] .filter((need) => need.status !== "retired") .sort(sortAffectByStatusAndIntensity); - const bonds = [...state.faceAffect.socialBonds] - .filter((bond) => bond.status !== "retired") - .sort(sortAffectByStatusAndIntensity); - const statusReads = [...state.faceAffect.statusReads] - .filter((read) => !read.retiredAt) - .sort(sortAffectByStatusAndIntensity); - const moodDimensions = [...state.faceAffect.moodDimensions] - .sort((left, right) => right.value - left.value); const agencyPressures = [...state.agencyPressure.pressures] .filter((pressure) => pressure.status !== "retired") .sort(sortAffectByStatusAndIntensity); - const durableMemories = [...state.thoughtMemory.memories] - .filter((memory) => !memory.retiredAt) - .slice(-12) - .reverse(); - const shortTermResidue = [...state.thoughtMemory.shortTerm] - .filter((memory) => !memory.retiredAt) - .slice(-12) - .reverse(); const incubation = [...state.thoughtMemory.incubation] .filter((thread) => thread.status !== "retired") .sort((left, right) => right.maturation - left.maturation); @@ -1157,109 +1137,20 @@ function renderRepoFaceStatePacket( const recentReceipts = [...state.speechReceipts.recentReceipts] .slice(-6) .reverse(); - const activationFacts = renderRepoFaceActivationProfileFacts(profile.activationProfile); - const runtimeFacts = renderRepoFaceRuntimePressureFacts(name, state); + const typedSections = renderPersonaTypedStateSections({ identityName: name, state }); const humanClarityFacts = roomContext ? renderRepoFaceHumanClarityPressureFacts(identity, roomContext) : undefined; const clarityPressureActive = Boolean(humanClarityFacts); - const selfTexture = [ - ...privateNotes.map(projectPrivateNoteForMemorySurface), - ...values.map((value) => value.summary || value.label), - ] - .map(cleanCharacterFacingSentence) - .filter((entry) => entry.length > 0) - .slice(0, 18); - if (selfTexture.length > 0) { - lines.push(`Right now, ${name} is carrying this close to the skin: ${joinAsNarrativeList(selfTexture)}.`); - } - - if (activationFacts) { - lines.push(activationFacts); - } - - if (runtimeFacts) { - lines.push(runtimeFacts); - } - - if (needs.length > 0) { - lines.push([ - `${name}'s explicit needs and frictions:`, - ...needs.map((need) => { - const target = targetLabel(need.target); - const claimOrQuestion = need.claim - ? `Claim: ${asSentence(need.claim)}` - : need.question - ? `Question: ${asSentence(need.question)}` - : ""; - return [ - `- ${need.kind} need toward ${target} [${need.status}, intensity ${need.intensity.toFixed(2)}, valence ${need.valence.toFixed(2)}]: ${asSentence(need.summary)}`, - claimOrQuestion, - `Tension: ${asSentence(need.tension)}`, - `Behavioral pull: ${asSentence(need.actionImplication)}`, - ].filter(Boolean).join(" "); - }), - ].join("\n")); - } - - if (bonds.length > 0) { - lines.push([ - "The social map has teeth:", - ...bonds.map((bond) => { - const target = targetLabel(bond.target); - return [ - `- ${target} draws ${bond.stance} [${bond.status}, intensity ${bond.intensity.toFixed(2)}]: ${asSentence(bond.summary)}`, - `Read: ${asSentence(bond.claim)}`, - `Tension: ${asSentence(bond.tension)}`, - `Behavioral pull: ${asSentence(bond.actionImplication)}`, - ].join(" "); - }), - ].join("\n")); - } + lines.push(...typedSections.opening, ...typedSections.needs, ...typedSections.bonds); const relationshipFreshnessFacts = renderRepoFaceRelationshipFreshnessFacts(name, state, registryIdentities); if (relationshipFreshnessFacts) { lines.push(relationshipFreshnessFacts); } - if (statusReads.length > 0) { - lines.push([ - "Status in the swarm is part of the weather:", - ...statusReads.map((read) => { - const target = targetLabel(read.target); - return [ - `- Around ${target}, ${name} feels ${read.status} [intensity ${read.intensity.toFixed(2)}]: ${asSentence(read.summary)}`, - `Read: ${asSentence(read.claim)}`, - `Tension: ${asSentence(read.tension)}`, - `Behavioral pull: ${asSentence(read.actionImplication)}`, - ].join(" "); - }), - ].join("\n")); - } - - if (moodDimensions.length > 0) { - lines.push([ - "Mood dimensions currently bending the turn:", - ...moodDimensions.map((dimension) => - `- ${dimension.name}=${dimension.value.toFixed(2)}${dimension.source ? ` from ${cleanCharacterFacingSentence(dimension.source)}` : ""}`, - ), - ].join("\n")); - } - - if (durableMemories.length > 0) { - lines.push([ - "Durable memories that should still bias judgment:", - ...durableMemories.map((memory) => renderRepoFaceMemoryFact(name, memory)), - ].join("\n")); - } - - if (shortTermResidue.length > 0) { - lines.push([ - "Short-term residue waiting to settle:", - ...shortTermResidue.map((memory) => renderRepoFaceMemoryFact(name, memory)), - ].join("\n")); - } + lines.push(...typedSections.statusMoodMemory); const socialGraphFacts = renderRepoFaceSocialGraphFacts(identity, registryIdentities, state); if (socialGraphFacts) { @@ -1382,7 +1273,7 @@ function renderRepoFaceStatePacket( return `You are ${name}, but your durable state is thin. Use the room, repo, and your jurisdiction to form a real opinion before speaking.`; } - return rejectLeakyMemorySurface(cleanRepoFaceProjectorLoopVocabulary(identity, lines.join("\n\n"))); + return validatePersonaMemorySurface(cleanRepoFaceProjectorLoopVocabulary(identity, lines.join("\n\n"))); } function renderRepoFaceSelfMaintenancePressureFacts( @@ -1611,83 +1502,6 @@ function targetLabel(target: { label?: string; id?: string; kind?: string } | un return target.label ?? target.id ?? target.kind ?? "an unnamed target"; } -function renderRepoFaceActivationProfileFacts( - activationProfile: VoidSelfStateTypedProjection["selfProfile"]["activationProfile"], -): string | undefined { - const sections = Object.entries(activationProfile) - .map(([section, values]) => { - const entries = Object.entries(values) - .sort(([, left], [, right]) => activationVectorWeight(right) - activationVectorWeight(left)) - .map(([key, value]) => `${key}=${activationVectorWeight(value).toFixed(2)}${activationVectorNote(value) ? ` (${cleanCharacterFacingSentence(activationVectorNote(value) ?? "")})` : ""}`); - return entries.length > 0 ? `- ${section}: ${entries.join("; ")}` : undefined; - }) - .filter((entry): entry is string => typeof entry === "string"); - - return sections.length > 0 - ? ["Activation profile that should color behavior:", ...sections].join("\n") - : undefined; -} - -function activationVectorWeight(value: unknown): number { - if (!isRecord(value)) { - return 0; - } - const candidates = [value.weight, value.current_activation, value.currentActivation, value.mean]; - const numeric = candidates.find((candidate) => typeof candidate === "number" && Number.isFinite(candidate)); - return typeof numeric === "number" ? numeric : 0; -} - -function activationVectorNote(value: unknown): string | undefined { - if (!isRecord(value)) { - return undefined; - } - return typeof value.note === "string" ? value.note : undefined; -} - -function renderRepoFaceRuntimePressureFacts( - name: string, - state: VoidSelfStateTypedProjection, -): string | undefined { - const lines: string[] = []; - const sleep = state.scheduledRuntime.sleepCycle; - if (sleep.isNapping || sleep.activeDreamThemes.length > 0) { - lines.push( - `${name}'s rest state: ${sleep.isNapping ? "currently in a sleep/low-output phase" : "awake but carrying dream residue"}${sleep.activeDreamThemes.length > 0 ? ` around ${joinAsNarrativeList(sleep.activeDreamThemes.map(cleanCharacterFacingSentence))}` : ""}.`, - ); - } - - const speaking = state.scheduledRuntime.speakingPressure; - const speakingParts = [ - `need to speak ${speaking.needToSpeak.toFixed(2)}`, - typeof speaking.confessionPressure === "number" ? `confession ${speaking.confessionPressure.toFixed(2)}` : "", - typeof speaking.noveltyPressure === "number" ? `novelty ${speaking.noveltyPressure.toFixed(2)}` : "", - typeof speaking.recentSpeechDamping === "number" ? `recent-speech damping ${speaking.recentSpeechDamping.toFixed(2)}` : "", - ].filter(Boolean); - lines.push(`Speaking pressure: ${speakingParts.join(", ")}. Treat this as appetite/restraint, not an order.`); - - if (state.scheduledRuntime.lastRuns.length > 0) { - lines.push(`Recent internal passes: ${state.scheduledRuntime.lastRuns.slice(-4).map((run) => - cleanCharacterFacingSentence(run.summary), - ).join(" | ")}`); - } - - return lines.length > 0 ? lines.join("\n") : undefined; -} - -function renderRepoFaceMemoryFact( - name: string, - memory: VoidSelfStateTypedProjection["thoughtMemory"]["memories"][number], -): string { - const parts = [ - `- ${memory.kind} about ${targetLabel(memory.target)}: ${asSentence(memory.summary)}`, - memory.claim ? `Claim: ${asSentence(memory.claim)}` : "", - memory.question ? `Question: ${asSentence(memory.question)}` : "", - memory.tension ? `Tension: ${asSentence(memory.tension)}` : "", - memory.actionImplication ? `Behavioral pull for ${name}: ${asSentence(memory.actionImplication)}` : "", - ]; - return parts.filter(Boolean).join(" "); -} - function renderRepoFaceRoomTextureFacts( identity: RepoDiscordIdentity, input: { @@ -2898,14 +2712,6 @@ function normalizeSocialLabel(value: string | undefined): string { return (value ?? "").toLowerCase().replace(/[^a-z0-9]/g, ""); } -function projectPrivateNoteForMemorySurface(note: string): string { - return note - .replace(/\bdo not prompt (?:her|him|them|it|[A-Z][A-Za-z0-9_-]*) as\b/gi, "she refuses to be treated as") - .replace(/\bdo not prompt\b/gi, "do not treat") - .replace(/\bprompt (?:her|him|them|it)\b/gi, "treat them") - .replace(/\bprompt [A-Z][A-Za-z0-9_-]*\b/g, "treat them"); -} - function cleanCharacterFacingSentence(value: string | undefined): string { const cleaned = (value ?? "") .replace(/\s*\|\s*/g, " ") diff --git a/scripts/smoke-persona-initiative-engine.ts b/scripts/smoke-persona-initiative-engine.ts index 74694f2..b4dcab5 100644 --- a/scripts/smoke-persona-initiative-engine.ts +++ b/scripts/smoke-persona-initiative-engine.ts @@ -65,7 +65,7 @@ import { import { readRepoActivity } from "../apps/persona-scheduler/dist/repo-activity-source.js"; import { readPersonaStateObservation } from "../apps/persona-scheduler/dist/persona-state-source.js"; import { readPersonaMemoryRecall } from "../apps/persona-scheduler/dist/persona-memory-context-source.js"; -import { projectPersonaMemorySurface } from "../apps/persona-scheduler/dist/persona-memory-projector.js"; +import { projectPersonaMemorySurface, renderPersonaTypedStateSections } from "../apps/persona-scheduler/dist/persona-memory-projector.js"; function participant(identityId: string, nextTurnAt: number): InitiativeParticipant { return { @@ -479,6 +479,10 @@ try { }); assert.equal(populatedObservation.status, "ok", "the source acquires typed mind and physiology facts from an existing CultCache surface"); assert.equal(populatedObservation.status === "ok" && populatedObservation.rest?.isNapping, false, "rest projection is deterministic at the supplied observation time"); + const typedSections = populatedObservation.status === "ok" + ? renderPersonaTypedStateSections({ identityName: "Nibu", state: populatedObservation.typedState }) + : undefined; + assert.match(typedSections?.opening.join("\n") ?? "", /Speaking pressure:/, "the projector owns typed runtime-pressure presentation without acquiring Persona state"); assert.deepEqual(await readFile(statePath), beforeObservation, "Persona state observation cannot rewrite sleep, speaking pressure, or any other Mind field"); } finally { await rm(stateSourceDirectory, { recursive: true, force: true }); diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 33296ed..209e4d0 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -414,3 +414,4 @@ {"ts":"2026-07-15T23:41:50Z","type":"implementation","status":"ok","note":"Extracted read-only Persona Body/Mind acquisition into persona-state-source.ts. Scheduler pulses now project current rest facts without writing sleep cycles or synthetic speaking pressure; memory rendering consumes the acquired typed observation. Smoke proves missing observation creates no file and existing .cc bytes remain unchanged."} {"ts":"2026-07-15T23:50:14Z","type":"implementation","status":"ok","note":"Extracted semantic Persona-memory vector refresh/query into persona-memory-context-source.ts. It consumes the existing PersonaStateObservation, returns typed hits/unavailability, and cannot reload canonical .cc state or render prompt prose. Deleted vector-store and recall-query mechanics from the heartbeat shell; smoke proves missing Mind fails before vector access."} {"ts":"2026-07-16T00:00:35Z","type":"implementation","status":"ok","note":"Extracted Persona memory projection policy into persona-memory-projector.ts. One boundary now owns deterministic/model selection, projector prompt construction, minimum output, and schema/path leak rejection through an injected text-model port; repo Faces and typed native Personas share it. Smoke proves model-free projection and negative leak rejection."} +{"ts":"2026-07-16T00:11:13Z","type":"implementation","status":"ok","note":"Moved the pure typed Persona-state core into persona-memory-projector.ts: identity texture, activation/runtime pressure, needs, bonds, status, mood, and durable/short-term memory. Deleted duplicate shell renderers and repaired the stale leak-validator reference. Execution-level --assemble-prompt nibu succeeded under file storage, covering the script path that tsc -b omits."} diff --git a/state/map.yaml b/state/map.yaml index 32b4e64..67d1915 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -278,4 +278,4 @@ rejected_paths: current_status: summary: VoidBot's bot/worker/provider/RAG/Postgres/Qdrant/CultCache structure is live. Repo Face/persona heartbeat jobs run through the direct `openai_api` provider configured for MiMo `mimo-v2.5-pro`, with the expensive state-projector pass still disabled. The 2026-07-04 transport repair replaced the old Bifrost HTTP/token bridge shortcut with typed Bifrost CultMesh Discord command and receipt documents advertised in the Bifrost provider store at `cultmesh://asgard.starfire.bifrost/commands/discord-post`. VoidBot stores the Bifrost target as a CultMesh URI, writes command docs to `E:/Projects/Bifrost/.bifrost/provider-store.cc`, optionally pumps Bifrost's command processor, and waits for typed receipts before completing repo Face Discord delivery. Bifrost's provider advertisement exposes `discord.post` command metadata for Odin/Eve agents, and a bounded Weksa live-fire completed visibly. Eve live state now runs end to end through CultLib dev retained publications, Hermodr ordered SSE, Eve component bindings, and VoidBot typed control state. Receipts acknowledge intent only. Heat initial load, provider-driven change, and browser-command change were visibly verified without reload through the same subscription. - next_action: Move the deterministic `renderRepoFaceStatePacket` family from `scripts/run-repo-face-heartbeats.ts` into `persona-memory-projector.ts`. Pass registry/social, room-weather, human-clarity, self-maintenance, and optional curiosity facts explicitly; keep curiosity retrieval and Discord acquisition outside the projector. + next_action: Move agency-pressure, incubation, candidate-intervention, and recent-speech sections into `persona-memory-projector.ts`, parameterized by the externally observed `clarityPressureActive` fact. Then make the shell pass social/room/clarity/maintenance/curiosity sections explicitly into a final projector-owned composition primitive.