diff --git a/apps/persona-scheduler/src/persona-state-source.ts b/apps/persona-scheduler/src/persona-state-source.ts new file mode 100644 index 0000000..d7479a0 --- /dev/null +++ b/apps/persona-scheduler/src/persona-state-source.ts @@ -0,0 +1,63 @@ +import { extname, resolve } from "node:path"; +import { access } from "node:fs/promises"; + +import { + loadVoidSelfStateTypedDocuments, + projectRepoFaceSleepCycleForNow, + resolveRepoFaceStatePath, + type RepoDiscordIdentity, + type RepoFaceRestSnapshot, + type VoidSelfStateTypedProjection, +} from "@voidbot/core"; + +export type PersonaStateObservation = + | { status: "ok"; identityId: string; statePath: string; typedState: VoidSelfStateTypedProjection; rest?: RepoFaceRestSnapshot } + | { status: "unconfigured" | "unsupported" | "missing"; identityId: string; statePath?: string; reason: string }; + +export async function readPersonaStateObservation(input: { + identity: RepoDiscordIdentity; + storageRoot: string; + now?: Date; +}): Promise { + const statePath = resolvePersonaStatePath(input.identity, input.storageRoot); + if (!statePath) return { status: "unconfigured", identityId: input.identity.id, reason: "No typed Persona state path is registered." }; + if (extname(statePath).toLowerCase() !== ".cc") { + return { status: "unsupported", identityId: input.identity.id, statePath, reason: "The registered Persona state is not a CultCache .cc surface." }; + } + try { + await access(statePath); + const typedState = await loadVoidSelfStateTypedDocuments({ + canonicalPath: statePath, + identity: { agentId: input.identity.id, publicName: input.identity.displayName, publicDescription: input.identity.description }, + }); + const projected = input.identity.identityKind === "native_persona" + ? undefined + : projectRepoFaceSleepCycleForNow(typedState.scheduledRuntime.sleepCycle, input.identity.id, input.now ?? new Date()); + return { + status: "ok", + identityId: input.identity.id, + statePath, + typedState, + rest: projected && { isNapping: projected.isNapping, napEndsAt: projected.napEndsAt, nextNapStartsAt: projected.nextNapStartsAt }, + }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return { status: "missing", identityId: input.identity.id, statePath, reason: "The registered Persona state surface does not exist." }; + } + throw error; + } +} + +export async function readPersonaStateObservations(input: { + identities: RepoDiscordIdentity[]; + storageRoot: string; + now?: Date; +}): Promise> { + const observations = await Promise.all(input.identities.map((identity) => readPersonaStateObservation({ identity, storageRoot: input.storageRoot, now: input.now }))); + return new Map(observations.map((observation) => [observation.identityId, observation])); +} + +function resolvePersonaStatePath(identity: RepoDiscordIdentity, storageRoot: string): string | undefined { + if (identity.identityKind === "native_persona") return identity.personaStatePath ? resolve(identity.personaStatePath) : undefined; + return resolveRepoFaceStatePath(identity, storageRoot); +} diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 85dd40f..892d5fc 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -149,6 +149,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - Persona job submission is isolated in `turn-actuator.ts`. That output port alone owns worker actor/guild context construction, `ContextBundle` lowering, the `repo-face-rumination` command, approval defaults, request IDs, and `createJob`; it returns a queue receipt and has no state-selection or prompt-composition authority. - Persona channel policy is isolated in `turn-routing.ts`. It owns pending-attention room preference, default/threshold fallback, snapshot neighborhoods, low-threshold topic projection, and bounded channel-speed projection; prompt/context code receives a route plan and does not choose rooms independently. - Operator control acquisition is isolated in `control-source.ts`. It owns pause-witness parsing and typed CultMesh swarm-heat loading with fail-closed validation; it reports facts while engine commits alone apply heat or record skipped ticks. +- 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. - 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 c381469..603b9bc 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/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, invokes external queue actuators, and still owns Persona physiology/memory context interpretation plus prompt assembly 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/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, invokes external queue actuators, and still owns Persona memory rendering/semantic recall plus prompt assembly 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 3fd5a9d..478b3a4 100644 --- a/scripts/run-repo-face-heartbeats.ts +++ b/scripts/run-repo-face-heartbeats.ts @@ -12,11 +12,8 @@ import { getRepoFaceSourceRepoName, getRepoDiscordIdentityAllowedChannelIds, faceRegistryAsRepoDiscordRegistry, - projectRepoFaceSleepCycleForNow, - applyVoidSelfStateOperation, loadFaceIdentityRegistry, loadVoidSelfStateTypedDocuments, - type RepoFaceRestSnapshot, resolveRepoFaceStatePath, type RepoFacePendingMention, type RepoDiscordIdentity, @@ -57,6 +54,11 @@ import { type PersonaSchedulerState as FaceHeartbeatState, } from "../apps/persona-scheduler/dist/state-store.js"; import { scanActivePersonaTurns } from "../apps/persona-scheduler/dist/active-turn-source.js"; +import { + readPersonaStateObservation, + readPersonaStateObservations, + type PersonaStateObservation, +} from "../apps/persona-scheduler/dist/persona-state-source.js"; import { readDiscordActivitySnapshot, type IdleCoolingSnapshot, @@ -144,8 +146,10 @@ async function main(): Promise { const faceRegistry = await loadFaceIdentityRegistry(config.repoDiscordIdentitiesPath); const registry = faceRegistryAsRepoDiscordRegistry(faceRegistry); const state = await readHeartbeatState(config.repoFaceHeartbeats.statePath); - const restStates = await loadRepoFaceRestStates(registry.identities, config.storageRoot, state, { dryRun }); const now = new Date(); + const personaStateObservations = await readPersonaStateObservations({ identities: registry.identities, storageRoot: config.storageRoot, now }); + const restStates = new Map(Array.from(personaStateObservations.entries()).flatMap(([identityId, observation]) => + observation.status === "ok" && observation.rest ? [[identityId, observation.rest] as const] : [])); advanceInitiativeClockFromWallClock(state, now); const activeTurnScan = dryRun ? { active: new Map(), staleRecovered: [] } @@ -250,6 +254,7 @@ async function main(): Promise { config, storage, queuedAt, + personaStateObservation: personaStateObservations.get(participant.identityId), }); if (turn.created) { @@ -346,6 +351,7 @@ async function queueParticipantTurn(input: { config: ReturnType; storage: Awaited>; queuedAt: string; + personaStateObservation?: PersonaStateObservation; }): Promise<{ created: boolean; activeJobId?: string; requestMessageId?: string; failureReason?: string }> { switch (input.participant.turnKind) { case "repo_face_rumination": @@ -366,6 +372,7 @@ async function queueRepoFaceTurn(input: { config: ReturnType; storage: Awaited>; queuedAt: string; + personaStateObservation?: PersonaStateObservation; }): Promise<{ created: boolean; activeJobId?: string; requestMessageId?: string; failureReason?: string }> { const identity = input.registryIdentities.find((entry) => entry.id === input.participant.identityId); if (!identity) { @@ -414,6 +421,7 @@ async function queueRepoFaceTurn(input: { input.registryIdentities, roomContext, humanPronounGuidance, + input.personaStateObservation, ); const repoActivitySurface = identity.identityKind === "native_persona" ? renderNativePersonaBodySurface(identity) @@ -474,190 +482,6 @@ async function queueRepoFaceTurn(input: { }; } -async function loadRepoFaceRestStates( - identities: RepoDiscordIdentity[], - storageRoot: string, - heartbeatState: FaceHeartbeatState, - options: { dryRun?: boolean } = {}, -): Promise> { - const restStates = new Map(); - const now = new Date(); - - for (const identity of identities) { - if (identity.identityKind === "native_persona") { - continue; - } - - try { - const statePath = resolveRepoFaceStatePath(identity, storageRoot); - const typedState = await loadVoidSelfStateTypedDocuments({ - canonicalPath: statePath, - identity: { - agentId: identity.id, - publicName: identity.displayName, - publicDescription: identity.description, - }, - }); - const projected = projectRepoFaceSleepCycleForNow( - typedState.scheduledRuntime.sleepCycle, - identity.id, - now, - ); - if (!options.dryRun && !sleepCyclesEqual(typedState.scheduledRuntime.sleepCycle, projected.sleepCycle)) { - await applyVoidSelfStateOperation( - { - canonicalPath: statePath, - identity: { - agentId: identity.id, - publicName: identity.displayName, - publicDescription: identity.description, - }, - }, - { - operation: "update_sleep_cycle", - sleepCycle: projected.sleepCycle, - }, - ); - } - const speakingPressure = buildRepoFaceSpeakingPressure( - typedState, - projected.sleepCycle, - now, - ); - if (!options.dryRun && !speakingPressuresEqual(typedState.scheduledRuntime.speakingPressure, speakingPressure)) { - await applyVoidSelfStateOperation( - { - canonicalPath: statePath, - identity: { - agentId: identity.id, - publicName: identity.displayName, - publicDescription: identity.description, - }, - }, - { - operation: "update_speaking_pressure", - speakingPressure, - }, - ); - } - restStates.set(identity.id, { - isNapping: projected.isNapping, - napEndsAt: projected.napEndsAt, - nextNapStartsAt: projected.nextNapStartsAt, - }); - } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if (code !== "ENOENT") { - throw error; - } - } - } - - return restStates; -} - -function buildRepoFaceSpeakingPressure( - typedState: Awaited>, - sleepCycle: Awaited>["sleepCycle"], - now: Date, -): Awaited>["scheduledRuntime"]["speakingPressure"] { - const previous = typedState.scheduledRuntime.speakingPressure; - const lastReceipt = typedState.speechReceipts.recentReceipts - .slice() - .sort((left, right) => Date.parse(right.sentAt) - Date.parse(left.sentAt)) - [0]; - const lastSpokeAt = lastReceipt?.sentAt ?? previous.lastSpokeAt; - const hoursSinceSpeech = lastSpokeAt ? Math.max(0, (now.getTime() - Date.parse(lastSpokeAt)) / 3_600_000) : 24; - const recentSpeechDamping = clamp(Math.exp(-hoursSinceSpeech / 3.5), 0, 1); - const affectNeedPressure = (typedState.faceAffect.needs ?? []) - .filter((entry) => entry.status === "active" || entry.status === "neglected") - .reduce((sum, entry) => { - const neglectedWeight = entry.status === "neglected" ? 1.25 : 1; - const substrateWeight = ["substrate", "agency", "status", "territory", "recognition"].includes(entry.kind) ? 0.18 : 0.11; - return sum + entry.intensity * substrateWeight * neglectedWeight; - }, 0); - const statusReadPressure = (typedState.faceAffect.statusReads ?? []) - .filter((entry) => !entry.retiredAt) - .reduce((sum, entry) => { - const sharpWeight = ["neglected", "bypassed", "blocked", "ignored", "threatened", "challenged"].includes(entry.status) ? 0.14 : 0.08; - return sum + entry.intensity * sharpWeight; - }, 0); - const socialBondPressure = (typedState.faceAffect.socialBonds ?? []) - .filter((entry) => entry.status === "active") - .reduce((sum, entry) => sum + entry.intensity * 0.07, 0); - const relationshipStalenessPressure = repoFaceRelationshipStalenessPressure(typedState, now); - const moodPressure = (typedState.faceAffect.moodDimensions ?? []) - .reduce((sum, entry) => { - const expressiveWeight = ["anger", "annoyance", "irritation", "envy", "pride", "smugness", "playfulness", "anxiety", "commandForce", "restlessness"].includes(entry.name) - ? 0.06 - : 0.025; - return sum + entry.value * expressiveWeight; - }, 0); - const agencyPressure = typedState.agencyPressure.pressures - .filter((entry) => entry.status === "active" || entry.status === "ready_to_act") - .reduce((sum, entry) => sum + entry.intensity * (entry.kind.includes("advocacy") ? 0.22 : 0.11), 0); - const candidatePressure = typedState.candidateInterventions.interventions - .filter((entry) => entry.status === "queued" || entry.status === "deferred") - .reduce((sum, entry) => sum + entry.priority * (entry.mustEventuallyShare ? 0.22 : 0.12), 0); - const silencePressure = clamp(hoursSinceSpeech / 8, 0, 1); - const sleepiness = sleepCycle.isNapping ? 0.22 : 0; - const targetNeed = clamp( - 0.12 + silencePressure * 0.18 + affectNeedPressure + statusReadPressure + socialBondPressure + relationshipStalenessPressure + moodPressure + agencyPressure + candidatePressure - recentSpeechDamping * 0.24 - sleepiness, - 0, - 1, - ); - const needToSpeak = round3(clamp((previous.needToSpeak ?? 0.25) * 0.58 + targetNeed * 0.42, 0, 1)); - - return { - needToSpeak, - confessionPressure: round3(clamp((previous.confessionPressure ?? 0.2) * 0.7 + moodPressure * 0.42 + socialBondPressure * 0.18 + relationshipStalenessPressure * 0.18, 0, 1)), - noveltyPressure: round3(clamp((previous.noveltyPressure ?? 0.25) * 0.62 + affectNeedPressure * 0.35 + statusReadPressure * 0.24 + relationshipStalenessPressure * 0.22 + candidatePressure * 0.28, 0, 1)), - recentSpeechDamping: round3(recentSpeechDamping), - lastSpokeAt, - }; -} - -function repoFaceRelationshipStalenessPressure( - typedState: VoidSelfStateTypedProjection, - now: Date, -): number { - const nowMs = now.getTime(); - const bondPressure = (typedState.faceAffect.socialBonds ?? []) - .filter((entry) => entry.status === "active" && entry.target.kind === "person") - .reduce((sum, entry) => { - const ageHours = ageHoursSince(entry.updatedAt, nowMs); - if (ageHours < 48) { - return sum; - } - return sum + clamp((ageHours - 48) / 120, 0, 1) * entry.intensity * 0.13; - }, 0); - const statusPressure = (typedState.faceAffect.statusReads ?? []) - .filter((entry) => !entry.retiredAt && entry.target.kind === "person") - .reduce((sum, entry) => { - const ageHours = ageHoursSince(entry.updatedAt, nowMs); - if (ageHours < 72) { - return sum; - } - return sum + clamp((ageHours - 72) / 144, 0, 1) * entry.intensity * 0.08; - }, 0); - return clamp(bondPressure + statusPressure, 0, 0.28); -} - -function speakingPressuresEqual( - left: Awaited>["scheduledRuntime"]["speakingPressure"], - right: Awaited>["scheduledRuntime"]["speakingPressure"], -): boolean { - return left.needToSpeak === right.needToSpeak - && left.confessionPressure === right.confessionPressure - && left.noveltyPressure === right.noveltyPressure - && left.recentSpeechDamping === right.recentSpeechDamping - && left.lastSpokeAt === right.lastSpokeAt; -} - -function sleepCyclesEqual(left: unknown, right: unknown): boolean { - return JSON.stringify(left) === JSON.stringify(right); -} - async function startVoidModerationTurn(input: { queuedAt: string; storageRoot: string; @@ -1019,6 +843,7 @@ async function renderRepoFaceMemorySurfaceForTurn( channelSnapshots: ChannelSnapshot[]; }, humanPronounGuidance?: RepoFaceHumanPronounGuidance[], + observation?: PersonaStateObservation, ): Promise { if (identity.identityKind === "native_persona") { return renderNativePersonaMemorySurface( @@ -1027,11 +852,13 @@ async function renderRepoFaceMemorySurfaceForTurn( registryIdentities, roomContext, humanPronounGuidance ?? await loadRepoFaceHumanPronounGuidance(config, roomContext), + observation, ); } - const statePath = resolveRepoFaceStatePath(identity, config.storageRoot); - const typedState = await loadVoidSelfStateTypedDocuments({ canonicalPath: statePath }); + const acquired = observation ?? await readPersonaStateObservation({ identity, storageRoot: config.storageRoot }); + if (acquired.status !== "ok") throw new Error(`${identity.displayName} Persona state ${acquired.status}: ${acquired.reason}`); + const typedState = acquired.typedState; const curiosityGraphFacts = roomContext ? await renderRepoFaceCuriosityGraphFacts(identity, config, typedState, roomContext) : undefined; @@ -1350,6 +1177,7 @@ async function renderNativePersonaMemorySurface( channelSnapshots: ChannelSnapshot[]; }, humanPronounGuidance: RepoFaceHumanPronounGuidance[] = [], + observation?: PersonaStateObservation, ): Promise { const personaStatePath = identity.personaStatePath; if (!personaStatePath) { @@ -1360,14 +1188,9 @@ async function renderNativePersonaMemorySurface( } if (extname(personaStatePath).toLowerCase() === ".cc") { - const typedState = await loadVoidSelfStateTypedDocuments({ - canonicalPath: resolve(personaStatePath), - identity: { - agentId: identity.id, - publicName: identity.displayName, - publicDescription: identity.description, - }, - }); + const acquired = observation ?? await readPersonaStateObservation({ identity, storageRoot: config.storageRoot }); + if (acquired.status !== "ok") throw new Error(`${identity.displayName} Persona state ${acquired.status}: ${acquired.reason}`); + const typedState = acquired.typedState; const statePacket = renderRepoFaceStatePacket( identity, typedState, diff --git a/scripts/smoke-persona-initiative-engine.ts b/scripts/smoke-persona-initiative-engine.ts index 529d83e..ecd18d1 100644 --- a/scripts/smoke-persona-initiative-engine.ts +++ b/scripts/smoke-persona-initiative-engine.ts @@ -1,10 +1,11 @@ import assert from "node:assert/strict"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { queueAgentHeartbeatMention, + ensureVoidSelfStateIdentityProfile, readRepoFaceMentionInbox, resolveRepoFaceHeartbeatDebugProjectionPath, resolveRepoFaceHeartbeatStatePath, @@ -62,6 +63,7 @@ import { readSwarmControlState, } from "../apps/persona-scheduler/dist/control-source.js"; import { readRepoActivity } from "../apps/persona-scheduler/dist/repo-activity-source.js"; +import { readPersonaStateObservation } from "../apps/persona-scheduler/dist/persona-state-source.js"; function participant(identityId: string, nextTurnAt: number): InitiativeParticipant { return { @@ -430,6 +432,32 @@ const routedIdentity = { speedMultiplier: 1, }], } as RepoDiscordIdentity; +const stateSourceDirectory = await mkdtemp(join(tmpdir(), "voidbot-persona-state-source-")); +try { + const statePath = join(stateSourceDirectory, "nibu.cc"); + const observation = await readPersonaStateObservation({ + identity: { ...routedIdentity, faceStatePath: statePath }, + storageRoot: stateSourceDirectory, + now: new Date("2026-07-15T21:00:00.000Z"), + }); + assert.equal(observation.status, "missing", "the Persona state source reports a missing canonical mind explicitly"); + await assert.rejects(access(statePath), "observing a missing Persona state cannot create or mutate its canonical surface"); + await ensureVoidSelfStateIdentityProfile({ + canonicalPath: statePath, + identity: { agentId: routedIdentity.id, publicName: routedIdentity.displayName, publicDescription: routedIdentity.description }, + }); + const beforeObservation = await readFile(statePath); + const populatedObservation = await readPersonaStateObservation({ + identity: { ...routedIdentity, faceStatePath: statePath }, + storageRoot: stateSourceDirectory, + now: new Date("2026-07-15T21:00:00.000Z"), + }); + 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"); + 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 }); +} const channelPlan = buildPersonaChannelPlan(routedIdentity, "aquarium", "lore"); assert.equal(channelPlan.primaryChannelId, "lore", "fresh direct attention chooses its permitted source room"); assert.deepEqual(channelPlan.snapshotChannelIds, ["aquarium", "lore", "legacy"], "routing exposes one deduplicated evidence neighborhood"); diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 5cd707a..e8b0e6c 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -411,3 +411,4 @@ {"ts":"2026-07-15T23:27:00Z","type":"implementation","status":"ok","note":"Persona scheduler persistence now has one typed CultCache owner: state-store.ts stores voidbot.persona_scheduler_state in repo-face-heartbeats.cc, canonicalizes legacy .json configuration, migrates the old JSON once with a storage_migrated witness, fails closed on malformed .cc, commits before attention-inbox acknowledgement, and emits JSON only as a derived dashboard/debug projection. Tests prove the projection cannot override canonical state and bot/scheduler mention paths converge on the same .cc inbox."} {"ts":"2026-07-15T23:29:00Z","type":"repair","status":"ok","note":"Applied the live swarm brake after Yggdrasil showed an accumulated ready backlog still dispatching one Persona per minute at heat 0.05. The paused branch exposed obsolete publishSwarmDashboardSurface calls whose renderer subprocess implementation had already been removed; deleted those calls because the resident swarm publisher watches the state projection and owns publication."} {"ts":"2026-07-15T23:33:06Z","type":"implementation","status":"ok","note":"Separated the resident one-minute observation pulse from Persona speech cadence: initiative selection now admits at most one unprompted turn per configured recovery window regardless of idle-rest state, while direct mentions bypass the cadence. Smoke covers active-room and idle-disabled negative paths."} +{"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."} diff --git a/state/map.yaml b/state/map.yaml index 5118a02..c81a8b2 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -65,7 +65,7 @@ active_subgoals: - Treat `notes/agent-swarm-teardown-plan-2026-05-21.md` as the historical teardown authority and the restart checklist. The repo Face swarm is live again, but only because the scheduler, prompt, model-output logs, parent Interpreter, Bifrost routing, and worker side-effect rails now have explicit observable boundaries. Keep watching for prompt/parser/transport Jenga before adding new swarm features. - Make the new project-state surfaces the default continuity path for nontrivial VoidBot work. - Keep the rebuilt moderation/self-state foundation on canonical CultCache `.cc` typed operations, never an editable JSON working projection. - - The resident `apps/persona-scheduler` process inside `voidbot.service` owns repo Face and native Persona turn pulses on Yggdrasil. Its `initiative-engine.ts` owns participant reconciliation, operator heat/speed projection, semantic-pressure commits, wall-clock advancement, active-turn freeze/completion recovery, queue-result commits, stale rescheduling, mention priority, rest/idle eligibility, and ready-order selection as a pure state machine. `state-store.ts` is the sole persistence/migration port: canonical state is one typed `voidbot.persona_scheduler_state` record in `repo-face-heartbeats.cc`; the old JSON shape is accepted only as a one-time migration source and emitted afterward only as a debug/dashboard projection. Missing state is explicit, malformed CultCache fails closed, and the backing store promotes atomic MessagePack writes. Discord attention crosses through immutable per-mention `voidbot.persona_attention_command` CultCache inbox documents resolved from that same canonical path; the bot creates commands, while the scheduler alone ingests, deduplicates, commits, and acknowledges them after durable state. The bot can no longer read-modify-write the whole heartbeat state. `active-turn-source.ts` is the narrow Postgres/legacy-lock adapter: it reports active job witnesses and marks truly stale queue claims failed, but it cannot mutate initiative. `discord-activity-source.ts` owns read-only Discord human-activity observation and idle-window derivation from explicit watched channels plus scheduler history; it cannot mutate initiative, consume attention, or select work. `semantic-pressure-source.ts` embeds eligible Persona affinity cards against recent permitted human messages and returns bounded pressure projections; only `initiative-engine.ts` may turn those facts into dynamic heat, readiness, interrupt receipts, or history. `turn-context-source.ts` owns raw current-room and nearby-channel Discord acquisition plus its bounded derived attachment cache; it returns chronological evidence and explicit snapshot failures without reading Persona state, composing prompts, or queuing work. The heartbeat orchestration script may project registered identities into neutral participant specs and affinity candidates and report external actuator results, but it cannot decide, persist, migrate, inspect queue liveness, poll Discord, commit semantic pressure, or overwrite initiative fields. The Windows `GameCult Local Orchestrator` no longer owns Persona scheduling, and its repo-Face task installer/wrapper have been deleted. Void moderation, mood, watchdog, and Bifrost dispatch remain separate organs pending their own daemon migration; they must not be smuggled back into the Persona scheduler. + - The resident `apps/persona-scheduler` process inside `voidbot.service` owns repo Face and native Persona turn pulses on Yggdrasil. Its `initiative-engine.ts` owns participant reconciliation, operator heat/speed projection, semantic-pressure commits, wall-clock advancement, active-turn freeze/completion recovery, queue-result commits, stale rescheduling, mention priority, rest/idle eligibility, and ready-order selection as a pure state machine. `state-store.ts` is the sole persistence/migration port: canonical state is one typed `voidbot.persona_scheduler_state` record in `repo-face-heartbeats.cc`; the old JSON shape is accepted only as a one-time migration source and emitted afterward only as a debug/dashboard projection. Missing state is explicit, malformed CultCache fails closed, and the backing store promotes atomic MessagePack writes. Discord attention crosses through immutable per-mention `voidbot.persona_attention_command` CultCache inbox documents resolved from that same canonical path; the bot creates commands, while the scheduler alone ingests, deduplicates, commits, and acknowledges them after durable state. The bot can no longer read-modify-write the whole heartbeat state. `active-turn-source.ts` is the narrow Postgres/legacy-lock adapter: it reports active job witnesses and marks truly stale queue claims failed, but it cannot mutate initiative. `persona-state-source.ts` owns read-only typed Persona-state acquisition and wall-clock physiology projection. It reports typed mind and current rest facts without creating a missing state surface or writing sleep/speaking-pressure updates; `initiative-engine.ts` alone decides whether those rest facts admit a turn. `discord-activity-source.ts` owns read-only Discord human-activity observation and idle-window derivation from explicit watched channels plus scheduler history; it cannot mutate initiative, consume attention, or select work. `semantic-pressure-source.ts` embeds eligible Persona affinity cards against recent permitted human messages and returns bounded pressure projections; only `initiative-engine.ts` may turn those facts into dynamic heat, readiness, interrupt receipts, or history. `turn-context-source.ts` owns raw current-room and nearby-channel Discord acquisition plus its bounded derived attachment cache; it returns chronological evidence and explicit snapshot failures without reading Persona state, composing prompts, or queuing work. The heartbeat orchestration script may project registered identities into neutral participant specs and affinity candidates and report external actuator results, but it cannot decide, persist, migrate, inspect queue liveness, poll Discord, commit semantic pressure, mutate Persona physiology, or overwrite initiative fields. The Windows `GameCult Local Orchestrator` no longer owns Persona scheduling, and its repo-Face task installer/wrapper have been deleted. Void moderation, mood, watchdog, and Bifrost dispatch remain separate organs pending their own daemon migration; they must not be smuggled back into the Persona scheduler. - `bifrost-governance-source.ts` owns the remaining Bifrost digest CLI adapter and converts command or parse failures into typed error topics. Persona prompt composition receives governance facts without knowing Bifrost process mechanics; `scripts/run-repo-face-heartbeats.ts` may not invoke the Bifrost CLI directly. - `initiative-engine.ts` is the only writer of scheduler state fields and history. Reconciliation, controls, pause/disabled skips, stale-turn recovery witnesses, semantic pressure, attention consumption, queue transitions, and tick finalization all cross named engine commit primitives. Queue/context actuators return results and cannot patch participants or history directly. - `turn-actuator.ts` owns lowering an assembled Persona prompt and evidence bundle into the canonical worker `ContextBundle` and approved `repo-face-rumination` job. It owns the worker actor, command, request ID, approval defaults, and `createJob` call, then returns only a queue receipt. The orchestration shell chooses no queue mechanics and the actuator cannot read Persona or initiative state. @@ -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: Extract Persona physiology/rest observation and memory-surface acquisition from `scripts/run-repo-face-heartbeats.ts` into one read-only source organ. Keep rest eligibility decisions in `initiative-engine.ts`; the source reports body/mind facts and cannot select, queue, or mutate initiative. + next_action: Extract Persona memory projection and semantic recall from `scripts/run-repo-face-heartbeats.ts` behind a memory-context organ that consumes the read-only `PersonaStateObservation`. Keep typed state acquisition in `persona-state-source.ts`, retrieval/index mechanics out of prompt composition, and queue authority in `turn-actuator.ts`.