diff --git a/apps/persona-scheduler/src/persona-social-context-projector.ts b/apps/persona-scheduler/src/persona-social-context-projector.ts index 4e48baf..0544b54 100644 --- a/apps/persona-scheduler/src/persona-social-context-projector.ts +++ b/apps/persona-scheduler/src/persona-social-context-projector.ts @@ -12,6 +12,113 @@ export interface PersonaHumanPronounGuidance { evidenceExcerpt?: string; } +export interface PersonaSocialContextProjection { + relationshipFreshness?: string; + socialGraph?: string; + peerOpening?: string; + socialPressure?: string; + pronouns?: string; + roomTexture?: string; + humanClarity?: string; +} + +export function projectPersonaSocialContext(input: { + identity: RepoDiscordIdentity; + registryIdentities: RepoDiscordIdentity[]; + state: VoidSelfStateTypedProjection; + recentMessages: SourceMessage[]; + channelSnapshots: ChannelSnapshot[]; + pronounGuidance: PersonaHumanPronounGuidance[]; + observedAt: Date; + topicAttractorFacts?: string; +}): PersonaSocialContextProjection { + return { + relationshipFreshness: renderPersonaRelationshipFreshness({ identityName: input.identity.displayName, state: input.state, registryIdentities: input.registryIdentities, observedAt: input.observedAt }), + socialGraph: renderPersonaSocialGraph(input), + peerOpening: renderPersonaPeerOpening(input), + socialPressure: renderPersonaRelationshipPressure(input), + pronouns: renderPersonaHumanPronounFacts(input.pronounGuidance), + roomTexture: renderPersonaRoomTexture(input), + humanClarity: renderPersonaHumanClarityPressure(input), + }; +} + +export function renderPersonaPeerOpening(input: { + identity: RepoDiscordIdentity; + registryIdentities: RepoDiscordIdentity[]; + recentMessages: SourceMessage[]; + channelSnapshots: ChannelSnapshot[]; +}): string | undefined { + const selfTokens = new Set(socialTokens(input.identity.displayName, input.identity.id, input.identity.repoName)); + const peersByToken = new Map(); + for (const peer of input.registryIdentities) for (const token of socialTokens(peer.displayName, peer.id, peer.repoName)) if (!selfTokens.has(token)) peersByToken.set(token, peer); + const entries = [ + ...input.recentMessages.map((message) => ({ label: "current room", message })), + ...input.channelSnapshots.flatMap((snapshot) => snapshot.messages.map((message) => ({ label: "nearby room", message }))), + ]; + const byPeer = new Map }>(); + for (const entry of entries) { + if (!entry.message.isBot || !entry.message.content.trim()) continue; + const peer = peersByToken.get(normalizeSocialLabel(entry.message.authorName)); + if (!peer) continue; + const bucket = byPeer.get(peer.id) ?? { peer, entries: [] }; + bucket.entries.push(entry); + byPeer.set(peer.id, bucket); + } + const facts = [...byPeer.values()].sort((left, right) => right.entries.length - left.entries.length).slice(0, 6).map(({ peer, entries: peerEntries }) => { + const latest = peerEntries.at(-1); + const labels = [...new Set(peerEntries.map((entry) => entry.label))].join(", "); + return `- ${peer.displayName}: ${peerEntries.length} recent nearby message${peerEntries.length === 1 ? "" : "s"} in ${labels}. Latest visible line: "${latest ? collapse(latest.message.content, 180) : ""}"`; + }); + return facts.length === 0 ? undefined : ["Recent peer openings for possible social reads:", ...facts, "These are raw openings for the projector to translate into possible trust, irritation, rivalry, alliance, or no social move at all. Do not treat them as consensus."].join("\n"); +} + +export function renderPersonaRelationshipPressure(input: { + identity: RepoDiscordIdentity; + registryIdentities: RepoDiscordIdentity[]; + state: VoidSelfStateTypedProjection; + recentMessages: SourceMessage[]; + channelSnapshots: ChannelSnapshot[]; +}): string | undefined { + const selfTokens = pressureTokensForIdentity(input.identity); + const jurisdictionTokens = pressureTokens(input.identity.repoName, input.identity.displayName, input.identity.description, ...input.identity.channelPermissions.flatMap((permission) => [permission.label, permission.topic])).filter((token) => token.length >= 5); + const peerProfiles = input.registryIdentities.filter((peer) => normalizeSocialLabel(peer.id) !== normalizeSocialLabel(input.identity.id)).map((peer) => ({ identity: peer, tokens: pressureTokensForIdentity(peer) })); + const relationTargets = collectPersonaSocialRelations(input.state).map((relation) => ({ label: relation.targetLabel, tokens: pressureTokens(relation.targetLabel) })).filter((relation) => relation.tokens.length > 0); + const entries = [ + ...input.recentMessages.map((message) => ({ label: "current room", message })), + ...input.channelSnapshots.flatMap((snapshot) => snapshot.messages.map((message) => ({ label: "nearby room", message }))), + ]; + const byId = new Map(); + for (const entry of entries) { + const content = collapse(entry.message.content, 10_000); + if (!content) continue; + const normalizedContent = normalizeSocialLabel(content); + const authorToken = normalizeSocialLabel(entry.message.authorName ?? entry.message.authorId); + const signals: string[] = []; + let score = 0; + if (tokenAppears(normalizedContent, selfTokens)) { score += 3; signals.push(`names ${input.identity.displayName}`); } + else if (tokenAppears(authorToken, selfTokens)) { score += 1; signals.push(`${input.identity.displayName}'s own recent line`); } + const peerMatches = peerProfiles.filter((peer) => tokenAppears(authorToken, peer.tokens) || tokenAppears(normalizedContent, peer.tokens)).slice(0, 3); + if (peerMatches.length > 0) { score += peerMatches.length; signals.push(`touches peer ${peerMatches.map((peer) => peer.identity.displayName).join("/")}`); } + const relationMatches = relationTargets.filter((relation) => tokenAppears(authorToken, relation.tokens) || tokenAppears(normalizedContent, relation.tokens)).slice(0, 3); + if (relationMatches.length > 0) { score += relationMatches.length; signals.push(`touches existing social target ${relationMatches.map((relation) => relation.label).join("/")}`); } + if (tokenAppears(normalizedContent, jurisdictionTokens)) { score += 1; signals.push("touches this jurisdiction or its domain language"); } + const kinds = pressureLanguageKinds(content); + if (kinds.length > 0) { score += 2; signals.push(`uses social/status language (${kinds.join(", ")})`); } + if (!entry.message.isBot && score > 0) { score += 1; signals.push("human voice"); } + if (score < 4) continue; + const existing = byId.get(entry.message.id); + if (!existing || score > existing.score) byId.set(entry.message.id, { label: entry.label, message: entry.message, score, signals: [...new Set(signals)] }); + } + const facts = [...byId.values()].sort((left, right) => Date.parse(left.message.timestamp) - Date.parse(right.message.timestamp) || left.message.id.localeCompare(right.message.id)).slice(-8); + if (facts.length === 0) return undefined; + return [ + "Recent relationship-pressure evidence:", + ...facts.map((fact) => `- [${fact.label}] ${fact.message.isBot ? `${fact.message.authorName} (agent/bot)` : fact.message.authorName} said: "${collapse(fact.message.content, 260)}" Signals: ${fact.signals.join("; ")}.`), + "These are raw provocations, not settled memories. Project them as tentative felt pressure only where this character's values, territory, current mood, or existing relationships make them matter.", + ].join("\n"); +} + export function renderPersonaHumanPronounFacts(guidance: PersonaHumanPronounGuidance[]): string | undefined { if (guidance.length === 0) return undefined; return [ @@ -168,6 +275,10 @@ function addRelation(map: Map): 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(); } +function pressureTokensForIdentity(identity: RepoDiscordIdentity): string[] { return pressureTokens(identity.displayName, identity.id, identity.repoName); } +function pressureTokens(...values: Array): string[] { const tokens = new Set(); for (const value of values) { const normalized = normalizeSocialLabel(value); if (normalized.length >= 3) tokens.add(normalized); for (const part of (value ?? "").replace(/([a-z])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean)) { const token = normalizeSocialLabel(part); if (token.length >= 4) tokens.add(token); } } return [...tokens]; } +function tokenAppears(text: string, tokens: string[]): boolean { return tokens.some((token) => token.length > 0 && text.includes(token)); } +function pressureLanguageKinds(content: string): string[] { const text = content.toLowerCase(); const groups: Array<[string, RegExp]> = [["status", /\b(status|standing|rank|hierarchy|authority|overbearing|defer(?:red|ring)?|challenge[ds]?|humiliat(?:e|ed|ing)|respect)\b/], ["territory", /\b(turf|jurisdiction|steward(?:ship)?|custody|owner|ownership|belongs?|domain|lane|stepp(?:ed|ing)? on)\b/], ["consultation", /\b(consult(?:ed|ation|ing)?|ask(?:ed|ing)?|permission|bypass(?:ed|ing)?|decorative|flavo[u]?r theater|rubber[- ]?stamp)\b/], ["affiliation", /\b(friend(?:ship)?|rival(?:ry)?|alliance|resent(?:ment|s|ed|ing)?|trust|protect(?:ion|ive)?|envy|jealous|wrapped around)\b/], ["attention", /\b(attention|ignored|neglected|noticed|summon(?:ed|s)?|called out|directly challenged|approval)\b/]]; return groups.filter(([, pattern]) => pattern.test(text)).map(([kind]) => kind); } export interface PersonaRoomTextureObservation { total: number; diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index c2fa5ae..4506950 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -154,8 +154,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - Persona memory projection policy is isolated in `persona-memory-projector.ts`. It owns the deterministic/model choice, projector prompt template, minimum model-output invariant, and schema/path leak rejection through an injected text-model port. Repo Faces and typed native Personas use the same boundary. The large deterministic state-packet renderer is still in the heartbeat shell and is the next extraction target. - The pure typed-state core of that packet now also lives in `persona-memory-projector.ts`: private identity texture, activation vectors, runtime/rest/speaking pressure, needs, bonds, status reads, mood dimensions, and durable/short-term memories. The shell still owns agency/incubation/candidate/receipt rendering and the ordering of externally acquired social, room, clarity, maintenance, and curiosity facts; those are the remaining packet-builder debris. - `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. +- `persona-social-context-projector.ts` owns one aggregate social-context projection from supplied identity, registry, typed state, messages, pronoun guidance, and observation time. That result includes relationship freshness, mapped/unmapped topology, peer openings, relationship-pressure scoring, pronouns, room texture, and human-clarity pressure. Clarity evidence sorts on the real `SourceMessage.timestamp`; the heartbeat shell no longer owns social tokenization or scoring helpers. - 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 13019bd..75790c5 100644 --- a/notes/voidbot-current-system-map.md +++ b/notes/voidbot-current-system-map.md @@ -183,7 +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. +- Human-clarity chronology, social topology, peer openings, and relationship-pressure scoring now share the same social-context owner. The shell consumes one named projection result and contains no duplicate social scorer. - `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 d949a7d..a02afe5 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 { collectPersonaSocialRelations, observePersonaRoomTexture, renderPersonaHumanClarityPressure, renderPersonaHumanPronounFacts, renderPersonaRelationshipFreshness, renderPersonaRoomTexture, renderPersonaRoomWeather, renderPersonaSocialGraph, type PersonaHumanPronounGuidance as RepoFaceHumanPronounGuidance } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; +import { observePersonaRoomTexture, projectPersonaSocialContext, renderPersonaHumanPronounFacts, renderPersonaRoomWeather, type PersonaHumanPronounGuidance as RepoFaceHumanPronounGuidance } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; import { readDiscordActivitySnapshot, type IdleCoolingSnapshot, @@ -1132,32 +1132,17 @@ function renderRepoFaceStatePacket( .slice(-8) .reverse(); const typedSections = renderPersonaTypedStateSections({ identityName: name, state }); - const humanClarityFacts = roomContext - ? renderPersonaHumanClarityPressure({ identity, ...roomContext }) - : undefined; - const clarityPressureActive = Boolean(humanClarityFacts); - - const relationshipFreshnessFacts = renderPersonaRelationshipFreshness({ - identityName: name, - state, + const socialContext = projectPersonaSocialContext({ + identity, registryIdentities, + state, + recentMessages: roomContext?.recentMessages ?? [], + channelSnapshots: roomContext?.channelSnapshots ?? [], + pronounGuidance: humanPronounGuidance, observedAt: new Date(), + topicAttractorFacts: roomContext ? renderRepoFaceTopicAttractorFacts(identity, roomContext.recentMessages) : undefined, }); - const socialGraphFacts = renderPersonaSocialGraph({ identity, registryIdentities, state }); - const peerOpeningFacts = roomContext - ? renderRepoFacePeerOpeningFacts(identity, registryIdentities, roomContext) - : undefined; - const socialPressureFacts = roomContext - ? renderRepoFaceRelationshipPressureFacts(identity, registryIdentities, state, roomContext) - : undefined; - const pronounFacts = renderPersonaHumanPronounFacts(humanPronounGuidance); - const roomTextureFacts = roomContext - ? renderPersonaRoomTexture({ - identity, - ...roomContext, - topicAttractorFacts: renderRepoFaceTopicAttractorFacts(identity, roomContext.recentMessages), - }) - : undefined; + const clarityPressureActive = Boolean(socialContext.humanClarity); const selfMaintenancePressureFacts = !clarityPressureActive ? renderRepoFaceSelfMaintenancePressureFacts(name, agencyPressures, needs, candidateInterventions) @@ -1166,16 +1151,16 @@ function renderRepoFaceStatePacket( return composePersonaMemoryPacket({ identityName: name, typed: typedSections, - relationshipFreshness: relationshipFreshnessFacts, - socialGraph: socialGraphFacts, - peerOpening: peerOpeningFacts, - socialPressure: socialPressureFacts, - pronouns: pronounFacts, - roomTexture: roomTextureFacts, + relationshipFreshness: socialContext.relationshipFreshness, + socialGraph: socialContext.socialGraph, + peerOpening: socialContext.peerOpening, + socialPressure: socialContext.socialPressure, + pronouns: socialContext.pronouns, + roomTexture: socialContext.roomTexture, curiosity: curiosityGraphFacts, selfMaintenance: selfMaintenancePressureFacts, pressureSections: renderPersonaPressureSections({ identityName: name, state, clarityPressureActive }), - humanClarity: humanClarityFacts, + humanClarity: socialContext.humanClarity, transformSurface: (surface) => cleanRepoFaceProjectorLoopVocabulary(identity, surface), }); } @@ -1800,261 +1785,6 @@ function formatSignal(value: number): string { return `low ${value.toFixed(2)}`; } -function renderRepoFacePeerOpeningFacts( - identity: RepoDiscordIdentity, - registryIdentities: RepoDiscordIdentity[], - roomContext: { - recentMessages: SourceMessage[]; - channelSnapshots: ChannelSnapshot[]; - }, -): string | undefined { - const selfTokens = new Set(socialTargetTokens(identity.displayName, identity.id, identity.repoName)); - const peersByToken = new Map(); - for (const peer of registryIdentities) { - for (const token of socialTargetTokens(peer.displayName, peer.id, peer.repoName)) { - if (!selfTokens.has(token)) { - peersByToken.set(token, peer); - } - } - } - - const entries: Array<{ label: string; message: SourceMessage }> = [ - ...roomContext.recentMessages.map((message) => ({ label: "current room", message })), - ...roomContext.channelSnapshots.flatMap((snapshot) => - snapshot.messages.map((message) => ({ label: "nearby room", message })), - ), - ]; - const byPeer = new Map }>(); - - for (const entry of entries) { - if (!entry.message.isBot || !entry.message.content.trim()) { - continue; - } - const peer = peersByToken.get(normalizeSocialLabel(entry.message.authorName)); - if (!peer) { - continue; - } - const bucket = byPeer.get(peer.id) ?? { peer, entries: [] }; - bucket.entries.push(entry); - byPeer.set(peer.id, bucket); - } - - const peerFacts = [...byPeer.values()] - .sort((left, right) => right.entries.length - left.entries.length) - .slice(0, 6) - .map(({ peer, entries }) => { - const latest = entries.at(-1); - const channelLabels = [...new Set(entries.map((entry) => entry.label))].join(", "); - const excerpt = latest ? collapseWhitespace(latest.message.content, 180) : ""; - return `- ${peer.displayName}: ${entries.length} recent nearby message${entries.length === 1 ? "" : "s"} in ${channelLabels}. Latest visible line: "${excerpt}"`; - }); - - if (peerFacts.length === 0) { - return undefined; - } - - return [ - "Recent peer openings for possible social reads:", - ...peerFacts, - "These are raw openings for the projector to translate into possible trust, irritation, rivalry, alliance, or no social move at all. Do not treat them as consensus.", - ].join("\n"); -} - -function renderRepoFaceRelationshipPressureFacts( - identity: RepoDiscordIdentity, - registryIdentities: RepoDiscordIdentity[], - state: VoidSelfStateTypedProjection, - roomContext: { - recentMessages: SourceMessage[]; - channelSnapshots: ChannelSnapshot[]; - }, -): string | undefined { - const selfTokens = socialPressureTokensForIdentity(identity); - const jurisdictionTokens = socialPressureJurisdictionTokens(identity); - const peerProfiles = registryIdentities - .filter((peer) => normalizeSocialLabel(peer.id) !== normalizeSocialLabel(identity.id)) - .map((peer) => ({ - identity: peer, - tokens: socialPressureTokensForIdentity(peer), - })); - const relationTargets = collectPersonaSocialRelations(state) - .map((relation) => ({ - label: relation.targetLabel, - tokens: socialPressureTokens(relation.targetLabel), - })) - .filter((relation) => relation.tokens.length > 0); - const entries: Array<{ label: string; message: SourceMessage }> = [ - ...roomContext.recentMessages.map((message) => ({ label: "current room", message })), - ...roomContext.channelSnapshots.flatMap((snapshot) => - snapshot.messages.map((message) => ({ label: "nearby room", message })), - ), - ]; - const byId = new Map(); - - for (const entry of entries) { - const content = collapseWhitespace(entry.message.content, 10_000); - if (!content) { - continue; - } - const normalizedContent = normalizeSocialLabel(content); - const authorToken = normalizeSocialLabel(entry.message.authorName ?? entry.message.authorId); - const signals: string[] = []; - let score = 0; - - const authorIsSelf = tokenAppearsInNormalizedText(authorToken, selfTokens); - const contentNamesSelf = tokenAppearsInNormalizedText(normalizedContent, selfTokens); - if (contentNamesSelf) { - score += 3; - signals.push(`names ${identity.displayName}`); - } else if (authorIsSelf) { - score += 1; - signals.push(`${identity.displayName}'s own recent line`); - } - - const peerMatches = peerProfiles - .filter((peer) => - tokenAppearsInNormalizedText(authorToken, peer.tokens) || - tokenAppearsInNormalizedText(normalizedContent, peer.tokens), - ) - .slice(0, 3); - if (peerMatches.length > 0) { - score += peerMatches.length; - signals.push(`touches peer ${peerMatches.map((peer) => peer.identity.displayName).join("/")}`); - } - - const relationMatches = relationTargets - .filter((relation) => - tokenAppearsInNormalizedText(authorToken, relation.tokens) || - tokenAppearsInNormalizedText(normalizedContent, relation.tokens), - ) - .slice(0, 3); - if (relationMatches.length > 0) { - score += relationMatches.length; - signals.push(`touches existing social target ${relationMatches.map((relation) => relation.label).join("/")}`); - } - - if (tokenAppearsInNormalizedText(normalizedContent, jurisdictionTokens)) { - score += 1; - signals.push("touches this jurisdiction or its domain language"); - } - - const socialPressureKinds = socialPressureLanguageKinds(content); - if (socialPressureKinds.length > 0) { - score += 2; - signals.push(`uses social/status language (${socialPressureKinds.join(", ")})`); - } - - if (!entry.message.isBot && score > 0) { - score += 1; - signals.push("human voice"); - } - - if (score < 4) { - continue; - } - - const existing = byId.get(entry.message.id); - if (!existing || score > existing.score) { - byId.set(entry.message.id, { - label: entry.label, - message: entry.message, - score, - signals: [...new Set(signals)], - }); - } - } - - const facts = [...byId.values()] - .sort((left, right) => { - const leftMs = Date.parse(left.message.timestamp); - const rightMs = Date.parse(right.message.timestamp); - if (Number.isFinite(leftMs) && Number.isFinite(rightMs) && leftMs !== rightMs) { - return leftMs - rightMs; - } - return left.message.id.localeCompare(right.message.id); - }) - .slice(-8); - - if (facts.length === 0) { - return undefined; - } - - return [ - "Recent relationship-pressure evidence:", - ...facts.map((fact) => { - const speaker = fact.message.isBot ? `${fact.message.authorName} (agent/bot)` : fact.message.authorName; - return `- [${fact.label}] ${speaker} said: "${collapseWhitespace(fact.message.content, 260)}" Signals: ${fact.signals.join("; ")}.`; - }), - "These are raw provocations, not settled memories. Project them as tentative felt pressure only where this character's values, territory, current mood, or existing relationships make them matter.", - ].join("\n"); -} - -function socialPressureTokensForIdentity(identity: RepoDiscordIdentity): string[] { - return socialPressureTokens(identity.displayName, identity.id, identity.repoName); -} - -function socialPressureJurisdictionTokens(identity: RepoDiscordIdentity): string[] { - return socialPressureTokens( - identity.repoName, - identity.displayName, - identity.description, - ...identity.channelPermissions.flatMap((permission) => [permission.label, permission.topic]), - ) - .filter((token) => token.length >= 5); -} - -function socialPressureTokens(...values: Array): string[] { - const tokens = new Set(); - for (const value of values) { - const normalized = normalizeSocialLabel(value); - if (normalized.length >= 3) { - tokens.add(normalized); - } - for (const part of splitSocialPressureWords(value)) { - const token = normalizeSocialLabel(part); - if (token.length >= 4) { - tokens.add(token); - } - } - } - return [...tokens]; -} - -function splitSocialPressureWords(value: string | undefined): string[] { - return (value ?? "") - .replace(/([a-z])([A-Z])/g, "$1 $2") - .split(/[^A-Za-z0-9]+/) - .map((part) => part.trim()) - .filter(Boolean); -} - -function tokenAppearsInNormalizedText(normalizedText: string, tokens: string[]): boolean { - return tokens.some((token) => token.length > 0 && normalizedText.includes(token)); -} - -function socialPressureLanguageKinds(content: string): string[] { - const text = content.toLowerCase(); - const kinds: string[] = []; - const groups: Array<[string, RegExp]> = [ - ["status", /\b(status|standing|rank|hierarchy|authority|overbearing|defer(?:red|ring)?|challenge[ds]?|humiliat(?:e|ed|ing)|respect)\b/], - ["territory", /\b(turf|jurisdiction|steward(?:ship)?|custody|owner|ownership|belongs?|domain|lane|stepp(?:ed|ing)? on)\b/], - ["consultation", /\b(consult(?:ed|ation|ing)?|ask(?:ed|ing)?|permission|bypass(?:ed|ing)?|decorative|flavo[u]?r theater|rubber[- ]?stamp)\b/], - ["affiliation", /\b(friend(?:ship)?|rival(?:ry)?|alliance|resent(?:ment|s|ed|ing)?|trust|protect(?:ion|ive)?|envy|jealous|wrapped around)\b/], - ["attention", /\b(attention|ignored|neglected|noticed|summon(?:ed|s)?|called out|directly challenged|approval)\b/], - ]; - for (const [kind, pattern] of groups) { - if (pattern.test(text)) { - kinds.push(kind); - } - } - return kinds; -} - async function loadRepoFaceHumanPronounGuidance( config: ReturnType, roomContext?: { @@ -2141,10 +1871,6 @@ function pronounEvidenceRank(profile: InteractionMemoryProfile, entry: Interacti return resolvedSetBonus + (sourceRank[entry.source] ?? 0) + stanceBonus + confidenceBonus + recencyBonus; } -function socialTargetTokens(...values: Array): string[] { - return [...new Set(values.map(normalizeSocialLabel).filter((value) => value.length > 0))]; -} - 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 7d7773d..d31a641 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, renderPersonaHumanClarityPressure, renderPersonaHumanPronounFacts, renderPersonaRoomWeather, renderPersonaSocialGraph } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; +import { observePersonaRoomTexture, projectPersonaSocialContext, renderPersonaHumanClarityPressure, renderPersonaHumanPronounFacts, renderPersonaRoomWeather, renderPersonaSocialGraph } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; function participant(identityId: string, nextTurnAt: number): InitiativeParticipant { return { @@ -505,6 +505,22 @@ try { ? 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 socialContext = populatedObservation.status === "ok" + ? projectPersonaSocialContext({ + identity: routedIdentity, + registryIdentities: [routedIdentity, { ...routedIdentity, id: "peer", repoName: "PeerRepo", displayName: "Peer" }], + state: populatedObservation.typedState, + recentMessages: [ + { id: "peer-opening", authorId: "peer", authorName: "Peer", content: "Nibu, the room is yours.", timestamp: "2026-07-15T21:01:00.000Z", isBot: true, channelId: "aquarium" }, + { id: "human-pressure", authorId: "human", authorName: "Operator", content: "Nibu, your authority over this jurisdiction is being challenged.", timestamp: "2026-07-15T21:02:00.000Z", isBot: false, channelId: "aquarium" }, + ], + channelSnapshots: [], + pronounGuidance: [], + observedAt: new Date("2026-07-15T21:03:00.000Z"), + }) + : undefined; + assert.match(socialContext?.peerOpening ?? "", /Peer: 1 recent nearby message/, "the aggregate social projection owns peer openings"); + assert.match(socialContext?.socialPressure ?? "", /human voice/, "the aggregate social projection owns relationship-pressure scoring"); const pressureSections = populatedObservation.status === "ok" ? renderPersonaPressureSections({ identityName: "Nibu", state: populatedObservation.typedState, clarityPressureActive: true }) : []; diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 0bd0c14..84e2a12 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -418,3 +418,4 @@ {"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."} +{"ts":"2026-07-16T00:57:11Z","type":"implementation","status":"ok","note":"Persona social context now has one aggregate projector owning freshness, topology, peer openings, relationship-pressure scoring, pronouns, room texture, and clarity from supplied facts; the heartbeat shell no longer owns duplicate social scorers. TypeScript build, aggregate smoke, exact Nibu prompt assembly (153917 chars), dry-run, and operator surface tests passed."} diff --git a/state/map.yaml b/state/map.yaml index 7b79705..217eb53 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 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`. + next_action: Extract self-maintenance pressure rendering from `scripts/run-repo-face-heartbeats.ts` behind a narrow projector boundary, then inspect whether curiosity-cluster construction belongs with its vector source or a separate curiosity projector.