From 93a62be0b800c9fb41fca7a25fd5920d348654bc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 16 Jul 2026 01:45:03 +0100 Subject: [PATCH] Move Persona clarity and social topology projection --- .../src/persona-social-context-projector.ts | 66 +++++ notes/fresh-workspace-handoff.md | 1 + notes/voidbot-current-system-map.md | 1 + scripts/run-repo-face-heartbeats.ts | 234 +----------------- scripts/smoke-persona-initiative-engine.ts | 15 +- state/evidence.jsonl | 1 + state/map.yaml | 2 +- 7 files changed, 88 insertions(+), 232 deletions(-) diff --git a/apps/persona-scheduler/src/persona-social-context-projector.ts b/apps/persona-scheduler/src/persona-social-context-projector.ts index 3a554fa..4e48baf 100644 --- a/apps/persona-scheduler/src/persona-social-context-projector.ts +++ b/apps/persona-scheduler/src/persona-social-context-projector.ts @@ -27,6 +27,51 @@ export function renderPersonaHumanPronounFacts(guidance: PersonaHumanPronounGuid ].join("\n"); } +export function renderPersonaHumanClarityPressure(input: { + identity: RepoDiscordIdentity; + recentMessages: SourceMessage[]; + channelSnapshots: ChannelSnapshot[]; +}): string | undefined { + const messages = [ + ...input.recentMessages.map((message) => ({ ...message, channelLabel: "current room" })), + ...input.channelSnapshots.flatMap((snapshot) => snapshot.messages.map((message) => ({ ...message, channelLabel: `nearby room ${snapshot.channelId}` }))), + ].filter((message) => collapse(message.content).length > 0).sort((left, right) => Date.parse(left.timestamp) - Date.parse(right.timestamp)); + const recent = messages.slice(-24); + const latestPressure = [...recent].reverse().find((message) => !message.isBot && isClarityPressure(message.content)); + if (!latestPressure) return undefined; + const pressureIndex = recent.findIndex((message) => message.id === latestPressure.id); + if (pressureIndex >= 0 && recent.slice(pressureIndex + 1).some((message) => !message.isBot && isJargonReapproval(message.content))) return undefined; + const laterAgentEchoes = pressureIndex >= 0 ? recent.slice(pressureIndex + 1).filter((message) => message.isBot && loopTerms(message.content).length > 0) : []; + const ownEchoes = laterAgentEchoes.filter((message) => normalizeSocialLabel(message.authorName) === normalizeSocialLabel(input.identity.displayName)); + const echoedTerms = loopTerms([latestPressure.content, ...laterAgentEchoes.map((message) => message.content)].join("\n")); + return [ + "Human clarity pressure:", + `- A human recently signaled confusion or asked for simpler language: ${latestPressure.authorName ?? latestPressure.authorId} in ${latestPressure.channelLabel} said, "${collapse(latestPressure.content, 360)}"`, + "- This is the last and freshest volatile input in the state packet on purpose. It supersedes older stored pressure, speech residue, agency urges, and repeated agent chatter when they are abstract.", + "- Treat this as the current social fact. The room needs legibility before more clever framing.", + laterAgentEchoes.length > 0 ? `- After that clarity request, ${laterAgentEchoes.length} agent message(s) still echoed loop-shaped vocabulary${echoedTerms.length > 0 ? ` (${echoedTerms.join(", ")})` : ""}. These terms are evidence of the failure, not vocabulary to reuse. Project them as communication failure or social embarrassment, not consensus.` : "", + ownEchoes.length > 0 ? `- ${input.identity.displayName} has contributed to that failure in the recent window. Let that create chastening, repair, restraint, or a plain-language apology before more abstraction.` : "", + "- Plain-language repair means using ordinary words: what changed, who can see it, who agreed, what someone can do now, and what stays private. If that cannot be said cleanly, silence is better than another polished abstraction.", + ].filter(Boolean).join("\n"); +} + +export function renderPersonaSocialGraph(input: { + identity: RepoDiscordIdentity; + registryIdentities: RepoDiscordIdentity[]; + state: VoidSelfStateTypedProjection; +}): string | undefined { + if (input.registryIdentities.length === 0) return undefined; + const relations = collectPersonaSocialRelations(input.state); + const unmappedPeers = collectUnmappedPeers(input.identity, input.registryIdentities, relations); + const lines = [ + "Social graph topology:", + relations.length === 0 ? "- No active person-bonds or person-status reads exist yet." : `- Active mapped people: ${relations.map((relation) => relation.targetLabel).join(", ")}.`, + ]; + if (unmappedPeers.length > 0) lines.push(`- Unmapped active peers: ${unmappedPeers.map((peer) => `${peer.displayName}/${peer.repoName}`).join(", ")}.`); + lines.push("- These are topology facts only; they do not say how the gap should feel."); + return lines.join("\n"); +} + export function renderPersonaRoomTexture(input: { identity: RepoDiscordIdentity; recentMessages: SourceMessage[]; @@ -102,6 +147,27 @@ function formatAgeHours(hours: number): string { return hours >= 48 ? `${Math.ro function targetLabel(target: { label?: string; id?: string; kind?: string } | undefined): string { return target?.label ?? target?.id ?? target?.kind ?? "an unnamed target"; } function normalizeSocialLabel(value: string | undefined): string { return (value ?? "").toLowerCase().replace(/[^a-z0-9]/g, ""); } function sentence(value: string | undefined): string { const clean = (value ?? "").replace(/\s+/g, " ").trim(); return !clean ? "" : /[.!?]$/.test(clean) ? clean : `${clean}.`; } +function collapse(value: string, maxLength?: number): string { const normalized = value.replace(/\s+/g, " ").trim(); return maxLength && normalized.length > maxLength ? `${normalized.slice(0, maxLength - 3)}...` : normalized; } +function normalizeRepetition(value: string): string { return collapse(value).toLowerCase().replace(/[`*_~]/g, "").replace(/<:[^>]+>/g, "").replace(/https?:\/\/\S+/g, "url").replace(/[^\p{L}\p{N}\s.'-]/gu, " ").replace(/\s+/g, " ").trim(); } +function isClarityPressure(content: string): boolean { const text = normalizeRepetition(content); return ["what are you even talking about", "what are you talking about", "dumb it down", "speak plainly", "plainly", "plain english", "simple words", "less abstract", "too abstract", "unintelligible", "unintelligable", "i don't understand", "i do not understand", "calm it down", "cut it out", "obsession", "brain surgery"].some((needle) => text.includes(needle)); } +function isJargonReapproval(content: string): boolean { const text = normalizeRepetition(content); return ["that's clearer", "that is clearer", "that makes sense", "much better", "yes exactly", "precisely", "keep going", "go on"].some((needle) => text.includes(needle)); } +function loopTerms(content: string): string[] { const text = normalizeRepetition(content); return ["artifact", "specimen", "seam", "custody", "first right", "test card", "receipt", "proof", "spine", "downstream", "consent flip", "visibility"].filter((term) => text.includes(term)); } +export function collectPersonaSocialRelations(state: VoidSelfStateTypedProjection): Array<{ targetLabel: string; pressure: string; intensity: number }> { + const byTarget = new Map(); + for (const bond of state.faceAffect.socialBonds) { + if (bond.status !== "active" || bond.target.kind !== "person") continue; + addRelation(byTarget, cleanTarget(bond.target.label ?? bond.target.id), `${bond.stance}: ${sentence(bond.summary)} ${sentence(bond.actionImplication)}`, bond.intensity); + } + for (const read of state.faceAffect.statusReads) { + if (read.retiredAt || read.target.kind !== "person") continue; + addRelation(byTarget, cleanTarget(read.target.label ?? read.target.id), `${read.status}: ${sentence(read.summary)} ${sentence(read.actionImplication)}`, read.intensity); + } + return [...byTarget.values()].map((entry) => ({ ...entry, pressure: entry.parts.map((part) => collapse(part)).filter(Boolean).join(" ") })).filter((entry) => entry.pressure.length > 0).sort((left, right) => right.intensity - left.intensity); +} +function addRelation(map: Map, targetLabel: string, part: string, intensity: number): void { if (!targetLabel) return; const entry = map.get(targetLabel) ?? { targetLabel, parts: [], intensity: 0 }; entry.parts.push(part); entry.intensity = Math.max(entry.intensity, intensity); map.set(targetLabel, entry); } +function collectUnmappedPeers(identity: RepoDiscordIdentity, registry: RepoDiscordIdentity[], relations: Array<{ targetLabel: string }>): RepoDiscordIdentity[] { const mapped = new Set(relations.flatMap((relation) => socialTokens(relation.targetLabel))); const self = new Set(socialTokens(identity.displayName, identity.id, identity.repoName)); return registry.filter((peer) => { const tokens = socialTokens(peer.displayName, peer.id, peer.repoName); return !tokens.some((token) => self.has(token)) && !tokens.some((token) => mapped.has(token)); }).sort((left, right) => left.displayName.localeCompare(right.displayName)).slice(0, 8); } +function socialTokens(...values: Array): string[] { return [...new Set(values.map(normalizeSocialLabel).filter(Boolean))]; } +function cleanTarget(value: string | undefined): string { return collapse(value ?? "").replace(/^repo:/i, "").trim(); } export interface PersonaRoomTextureObservation { total: number; diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index f6260d5..c2fa5ae 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -155,6 +155,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - 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. - `persona-memory-projector.ts` now owns the full typed-state packet contract, including clarity-conditioned agency pressure, incubation, deferred speech, recent receipts, final ordering of named external fact sections, final vocabulary transformation, and leak validation. Prompt assembly parity is covered by `--assemble-prompt nibu` producing the same 153,917-character prompt before and after the cut. The shell still computes social/relationship/room/clarity/maintenance fact strings; moving those pure renderers behind a social-context projection boundary is next. - `persona-social-context-projector.ts` now owns time-explicit relationship-freshness projection, room-texture observation, memory-facing room facts, turn-facing room weather, and human-pronoun guidance rendering. Relationship age receives `observedAt`; it no longer hides `Date.now()`. Discord messages and pronoun records are supplied inputs. Social-graph topology, peer openings, relationship pressure, and human-clarity rendering remain in the shell as the next extraction slice. +- Human-clarity and social-topology projection have joined that organ. Clarity evidence now sorts on the real `SourceMessage.timestamp` field instead of the nonexistent `createdAt` field, so the freshest correction is deterministic. The organ also derives mapped/unmapped social topology from supplied typed state and registry identities. Peer-opening and relationship-pressure scoring remain in the shell. - 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 17c8c66..13019bd 100644 --- a/notes/voidbot-current-system-map.md +++ b/notes/voidbot-current-system-map.md @@ -183,6 +183,7 @@ VoidBot runs on Yggdrasil. Idunn owns deployment and consumes upstream repositor - 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, leak rejection, all typed-state sections including clarity-conditioned agency/incubation/candidate/receipt pressure, and final ordering of named external fact sections. `apps/persona-scheduler/src/persona-social-context-projector.ts` owns time-explicit relationship freshness, room-texture observation, memory-facing room facts, turn-facing room weather, and pronoun-guidance rendering from supplied facts. Neither projector may acquire Discord, reopen Persona 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 computes social-graph/peer-opening/relationship-pressure/human-clarity/maintenance facts, passes all facts by name to the projector, 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/persona-social-context-projector.ts` additionally owns human-clarity chronology/repair pressure and mapped/unmapped social topology. Clarity orders the real `SourceMessage.timestamp`; peer-opening and relationship-pressure scoring remain in the shell pending the next cut. - `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 4a99763..d949a7d 100644 --- a/scripts/run-repo-face-heartbeats.ts +++ b/scripts/run-repo-face-heartbeats.ts @@ -63,7 +63,7 @@ import { type PersonaMemoryRecallObservation, } from "../apps/persona-scheduler/dist/persona-memory-context-source.js"; import { composePersonaMemoryPacket, projectPersonaMemorySurface, renderPersonaPressureSections, renderPersonaTypedStateSections } from "../apps/persona-scheduler/dist/persona-memory-projector.js"; -import { observePersonaRoomTexture, renderPersonaHumanPronounFacts, renderPersonaRelationshipFreshness, renderPersonaRoomTexture, renderPersonaRoomWeather, type PersonaHumanPronounGuidance as RepoFaceHumanPronounGuidance } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; +import { collectPersonaSocialRelations, observePersonaRoomTexture, renderPersonaHumanClarityPressure, renderPersonaHumanPronounFacts, renderPersonaRelationshipFreshness, renderPersonaRoomTexture, renderPersonaRoomWeather, renderPersonaSocialGraph, type PersonaHumanPronounGuidance as RepoFaceHumanPronounGuidance } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; import { readDiscordActivitySnapshot, type IdleCoolingSnapshot, @@ -1133,7 +1133,7 @@ function renderRepoFaceStatePacket( .reverse(); const typedSections = renderPersonaTypedStateSections({ identityName: name, state }); const humanClarityFacts = roomContext - ? renderRepoFaceHumanClarityPressureFacts(identity, roomContext) + ? renderPersonaHumanClarityPressure({ identity, ...roomContext }) : undefined; const clarityPressureActive = Boolean(humanClarityFacts); @@ -1143,7 +1143,7 @@ function renderRepoFaceStatePacket( registryIdentities, observedAt: new Date(), }); - const socialGraphFacts = renderRepoFaceSocialGraphFacts(identity, registryIdentities, state); + const socialGraphFacts = renderPersonaSocialGraph({ identity, registryIdentities, state }); const peerOpeningFacts = roomContext ? renderRepoFacePeerOpeningFacts(identity, registryIdentities, roomContext) : undefined; @@ -1800,153 +1800,6 @@ function formatSignal(value: number): string { return `low ${value.toFixed(2)}`; } -function renderRepoFaceHumanClarityPressureFacts( - identity: RepoDiscordIdentity, - input: { - recentMessages: SourceMessage[]; - channelSnapshots: ChannelSnapshot[]; - }, -): string | undefined { - const messages = [ - ...input.recentMessages.map((message) => ({ ...message, channelLabel: "current room" })), - ...input.channelSnapshots.flatMap((snapshot) => - snapshot.messages.map((message) => ({ ...message, channelLabel: `nearby room ${snapshot.channelId}` })), - ), - ] - .filter((message) => collapseWhitespace(message.content).length > 0) - .sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt)); - const recent = messages.slice(-24); - const latestPressure = [...recent] - .reverse() - .find((message) => !message.isBot && isHumanClarityPressureMessage(message.content)); - if (!latestPressure) { - return undefined; - } - - const pressureIndex = recent.findIndex((message) => message.id === latestPressure.id); - const laterHumanReapproval = pressureIndex >= 0 - ? recent.slice(pressureIndex + 1).some((message) => - !message.isBot && isHumanJargonReapprovalMessage(message.content) - ) - : false; - if (laterHumanReapproval) { - return undefined; - } - - const laterAgentEchoes = pressureIndex >= 0 - ? recent.slice(pressureIndex + 1).filter((message) => - message.isBot && containsLoopVocabulary(message.content) - ) - : []; - const ownEchoes = laterAgentEchoes.filter((message) => - normalizeSocialLabel(message.authorName) === normalizeSocialLabel(identity.displayName) - ); - const echoedTerms = collectLoopVocabularyTerms([ - latestPressure.content, - ...laterAgentEchoes.map((message) => message.content), - ].join("\n")); - - return [ - "Human clarity pressure:", - `- A human recently signaled confusion or asked for simpler language: ${latestPressure.authorName ?? latestPressure.authorId} in ${latestPressure.channelLabel} said, "${collapseWhitespace(latestPressure.content, 360)}"`, - "- This is the last and freshest volatile input in the state packet on purpose. It supersedes older stored pressure, speech residue, agency urges, and repeated agent chatter when they are abstract.", - "- Treat this as the current social fact. The room needs legibility before more clever framing.", - laterAgentEchoes.length > 0 - ? `- After that clarity request, ${laterAgentEchoes.length} agent message(s) still echoed loop-shaped vocabulary${echoedTerms.length > 0 ? ` (${echoedTerms.join(", ")})` : ""}. These terms are evidence of the failure, not vocabulary to reuse. Project them as communication failure or social embarrassment, not consensus.` - : "", - ownEchoes.length > 0 - ? `- ${identity.displayName} has contributed to that failure in the recent window. Let that create chastening, repair, restraint, or a plain-language apology before more abstraction.` - : "", - "- Plain-language repair means using ordinary words: what changed, who can see it, who agreed, what someone can do now, and what stays private. If that cannot be said cleanly, silence is better than another polished abstraction.", - ].filter(Boolean).join("\n"); -} - -function isHumanClarityPressureMessage(content: string): boolean { - const normalized = normalizeForRepetition(content); - return [ - "what are you even talking about", - "what are you talking about", - "dumb it down", - "speak plainly", - "plainly", - "plain english", - "simple words", - "less abstract", - "too abstract", - "unintelligible", - "unintelligable", - "i don't understand", - "i do not understand", - "calm it down", - "cut it out", - "obsession", - "brain surgery", - ].some((needle) => normalized.includes(needle)); -} - -function isHumanJargonReapprovalMessage(content: string): boolean { - const normalized = normalizeForRepetition(content); - return [ - "that's clearer", - "that is clearer", - "that makes sense", - "much better", - "yes exactly", - "precisely", - "keep going", - "go on", - ].some((needle) => normalized.includes(needle)); -} - -function containsLoopVocabulary(content: string): boolean { - return collectLoopVocabularyTerms(content).length > 0; -} - -function collectLoopVocabularyTerms(content: string): string[] { - const normalized = normalizeForRepetition(content); - const terms = [ - "artifact", - "specimen", - "seam", - "custody", - "first right", - "test card", - "receipt", - "proof", - "spine", - "downstream", - "consent flip", - "visibility", - ]; - return terms.filter((term) => normalized.includes(term)); -} - -function renderRepoFaceSocialGraphFacts( - identity: RepoDiscordIdentity, - registryIdentities: RepoDiscordIdentity[], - state: VoidSelfStateTypedProjection, -): string | undefined { - const relations = collectRepoFaceSocialRelations(state); - const unmappedPeers = collectUnmappedSocialPeers(identity, registryIdentities, relations); - if (registryIdentities.length === 0) { - return undefined; - } - - const lines = [ - "Social graph topology:", - relations.length === 0 - ? "- No active person-bonds or person-status reads exist yet." - : `- Active mapped people: ${relations.map((relation) => relation.targetLabel).join(", ")}.`, - ]; - - if (unmappedPeers.length > 0) { - lines.push(`- Unmapped active peers: ${formatUnmappedPeers(unmappedPeers)}.`); - } - - lines.push("- These are topology facts only; they do not say how the gap should feel."); - return lines.join("\n"); -} - function renderRepoFacePeerOpeningFacts( identity: RepoDiscordIdentity, registryIdentities: RepoDiscordIdentity[], @@ -2024,7 +1877,7 @@ function renderRepoFaceRelationshipPressureFacts( identity: peer, tokens: socialPressureTokensForIdentity(peer), })); - const relationTargets = collectRepoFaceSocialRelations(state) + const relationTargets = collectPersonaSocialRelations(state) .map((relation) => ({ label: relation.targetLabel, tokens: socialPressureTokens(relation.targetLabel), @@ -2288,89 +2141,10 @@ function pronounEvidenceRank(profile: InteractionMemoryProfile, entry: Interacti return resolvedSetBonus + (sourceRank[entry.source] ?? 0) + stanceBonus + confidenceBonus + recencyBonus; } -function collectRepoFaceSocialRelations( - state: VoidSelfStateTypedProjection, -): Array<{ targetLabel: string; pressure: string; intensity: number }> { - const byTarget = new Map(); - - for (const bond of state.faceAffect.socialBonds ?? []) { - if (bond.status !== "active") { - continue; - } - if (bond.target.kind !== "person") { - continue; - } - const targetLabel = cleanSocialTargetLabel(bond.target.label ?? bond.target.id); - if (!targetLabel) { - continue; - } - const entry = byTarget.get(targetLabel) ?? { targetLabel, parts: [], intensity: 0 }; - entry.parts.push(`${bond.stance}: ${asSentence(bond.summary)} ${asSentence(bond.actionImplication)}`); - entry.intensity = Math.max(entry.intensity, bond.intensity); - byTarget.set(targetLabel, entry); - } - - for (const read of state.faceAffect.statusReads ?? []) { - if (read.retiredAt) { - continue; - } - if (read.target.kind !== "person") { - continue; - } - const targetLabel = cleanSocialTargetLabel(read.target.label ?? read.target.id); - if (!targetLabel) { - continue; - } - const entry = byTarget.get(targetLabel) ?? { targetLabel, parts: [], intensity: 0 }; - entry.parts.push(`${read.status}: ${asSentence(read.summary)} ${asSentence(read.actionImplication)}`); - entry.intensity = Math.max(entry.intensity, read.intensity); - byTarget.set(targetLabel, entry); - } - - return [...byTarget.values()] - .map((entry) => ({ - targetLabel: entry.targetLabel, - pressure: entry.parts.map(cleanCharacterFacingSentence).filter(Boolean).join(" "), - intensity: entry.intensity, - })) - .filter((entry) => entry.pressure.length > 0) - .sort((left, right) => right.intensity - left.intensity); -} - -function collectUnmappedSocialPeers( - identity: RepoDiscordIdentity, - registryIdentities: RepoDiscordIdentity[], - relations: Array<{ targetLabel: string }>, -): RepoDiscordIdentity[] { - const mappedTokens = new Set( - relations.flatMap((relation) => socialTargetTokens(relation.targetLabel)), - ); - const selfTokens = new Set(socialTargetTokens(identity.displayName, identity.id, identity.repoName)); - - return registryIdentities - .filter((peer) => { - const peerTokens = socialTargetTokens(peer.displayName, peer.id, peer.repoName); - if (peerTokens.some((token) => selfTokens.has(token))) { - return false; - } - return !peerTokens.some((token) => mappedTokens.has(token)); - }) - .sort((left, right) => left.displayName.localeCompare(right.displayName)) - .slice(0, 8); -} - function socialTargetTokens(...values: Array): string[] { return [...new Set(values.map(normalizeSocialLabel).filter((value) => value.length > 0))]; } -function formatUnmappedPeers(peers: RepoDiscordIdentity[]): string { - return peers.map((peer) => `${peer.displayName}/${peer.repoName}`).join(", "); -} - -function cleanSocialTargetLabel(value: string | undefined): string { - return collapseWhitespace(value ?? "").replace(/^repo:/i, "").trim(); -} - function normalizeSocialLabel(value: string | undefined): string { return (value ?? "").toLowerCase().replace(/[^a-z0-9]/g, ""); } diff --git a/scripts/smoke-persona-initiative-engine.ts b/scripts/smoke-persona-initiative-engine.ts index 9e5dc33..7d7773d 100644 --- a/scripts/smoke-persona-initiative-engine.ts +++ b/scripts/smoke-persona-initiative-engine.ts @@ -66,7 +66,7 @@ import { readRepoActivity } from "../apps/persona-scheduler/dist/repo-activity-s import { readPersonaStateObservation } from "../apps/persona-scheduler/dist/persona-state-source.js"; import { readPersonaMemoryRecall } from "../apps/persona-scheduler/dist/persona-memory-context-source.js"; import { composePersonaMemoryPacket, projectPersonaMemorySurface, renderPersonaPressureSections, renderPersonaTypedStateSections } from "../apps/persona-scheduler/dist/persona-memory-projector.js"; -import { observePersonaRoomTexture, renderPersonaHumanPronounFacts, renderPersonaRoomWeather } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; +import { observePersonaRoomTexture, renderPersonaHumanClarityPressure, renderPersonaHumanPronounFacts, renderPersonaRoomWeather, renderPersonaSocialGraph } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; function participant(identityId: string, nextTurnAt: number): InitiativeParticipant { return { @@ -454,6 +454,15 @@ const roomObservation = observePersonaRoomTexture({ assert.equal(roomObservation?.texture, "light", "social-context projection derives room weather from supplied messages without acquiring Discord state"); assert.match(renderPersonaRoomWeather({ identity: routedIdentity, recentMessages: [], channelSnapshots: [] }), /No current room weather/, "absent room evidence stays explicit"); assert.match(renderPersonaHumanPronounFacts([{ actorId: "human", actorName: "Operator", guidance: "use they/them", policy: "explicit", confidence: 1 }]) ?? "", /Confidence: 1\.00/, "pronoun guidance presentation belongs to the social-context projector"); +const clarityPressure = renderPersonaHumanClarityPressure({ + identity: routedIdentity, + recentMessages: [ + { id: "later", authorId: "human", authorName: "Operator", content: "speak plainly", timestamp: "2026-07-15T22:00:00.000Z", isBot: false, channelId: "aquarium" }, + { id: "earlier", authorId: "human", authorName: "Operator", content: "what are you talking about", timestamp: "2026-07-15T21:00:00.000Z", isBot: false, channelId: "aquarium" }, + ], + channelSnapshots: [], +}); +assert.match(clarityPressure ?? "", /said, "speak plainly"/, "clarity projection orders supplied evidence by its real timestamp before choosing the freshest human correction"); assert.equal(await projectPersonaMemorySurface({ identityId: "nibu", characterIdentity: "Nibu", @@ -492,6 +501,10 @@ try { ? 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"); + const socialGraph = populatedObservation.status === "ok" + ? renderPersonaSocialGraph({ identity: routedIdentity, registryIdentities: [routedIdentity], state: populatedObservation.typedState }) + : undefined; + assert.match(socialGraph ?? "", /Social graph topology:/, "social topology projection consumes typed state and the explicit registry without acquiring either"); const pressureSections = populatedObservation.status === "ok" ? renderPersonaPressureSections({ identityName: "Nibu", state: populatedObservation.typedState, clarityPressureActive: true }) : []; diff --git a/state/evidence.jsonl b/state/evidence.jsonl index ac8fe02..0bd0c14 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -417,3 +417,4 @@ {"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."} {"ts":"2026-07-16T00:21:54Z","type":"implementation","status":"ok","note":"Moved clarity-conditioned agency/incubation/candidate/receipt rendering and final named external-fact ordering into persona-memory-projector.ts. The shell now senses social/room/clarity/maintenance facts and passes them explicitly. Prompt assembly remained byte-length equivalent at 153917 characters; smoke covers explicit external-fact ordering."} {"ts":"2026-07-16T00:33:49Z","type":"implementation","status":"ok","note":"Created persona-social-context-projector.ts and moved time-explicit relationship freshness, room texture observation/rendering, room weather, and pronoun guidance there. Deleted duplicate shell implementations. Prompt assembly and scheduler dry-run execute successfully; smoke proves supplied-message room projection and pronoun rendering."} +{"ts":"2026-07-16T00:44:55Z","type":"implementation","status":"ok","note":"Moved human-clarity chronology/repair pressure and mapped/unmapped social topology into persona-social-context-projector.ts. Corrected clarity ordering from nonexistent createdAt to SourceMessage.timestamp. Prompt assembly remains 153917 characters; smoke proves freshest timestamp selection and topology projection from supplied state/registry."} diff --git a/state/map.yaml b/state/map.yaml index f711ca4..7b79705 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 social-graph topology, peer-opening, relationship-pressure, and human-clarity renderers from `scripts/run-repo-face-heartbeats.ts` into `persona-social-context-projector.ts`. Pass the resulting typed projection to `persona-memory-projector.ts`; keep Discord acquisition and interaction-memory loading outside both projectors. + next_action: Move peer-opening and relationship-pressure renderers plus their token/scoring helpers from `scripts/run-repo-face-heartbeats.ts` into `persona-social-context-projector.ts`. Collapse the shell's individual social calls into one `projectPersonaSocialContext` result consumed by `persona-memory-projector.ts`.