diff --git a/apps/persona-scheduler/src/persona-turn-prompt-projector.ts b/apps/persona-scheduler/src/persona-turn-prompt-projector.ts new file mode 100644 index 0000000..8f5f63b --- /dev/null +++ b/apps/persona-scheduler/src/persona-turn-prompt-projector.ts @@ -0,0 +1,93 @@ +import { buildEpiphanyIdentityRegistry, type RepoDiscordIdentity, type RepoFacePendingMention } from "@voidbot/core"; +import { loadPromptTemplate, type SourceMessage } from "@voidbot/shared"; +import type { InitiativeParticipant } from "./initiative-engine.js"; +import type { PersonaChannelPlan } from "./turn-routing.js"; +import type { ChannelSnapshot } from "./turn-context-source.js"; +import type { BifrostGovernanceDigest } from "./bifrost-governance-source.js"; +import type { PersonaHumanPronounGuidance } from "./persona-social-context-projector.js"; +import { observePersonaRoomTexture, renderPersonaHumanPronounFacts, renderPersonaRoomWeather } from "./persona-social-context-projector.js"; +import { renderPersonaRoomTopicSaturation } from "./persona-conversation-projector.js"; + +export interface PersonaJurisdictionDiveDirective { due: boolean; cadence: number; promptLine: string; } + +export function buildPersonaTurnPrompt(input: { + identity: RepoDiscordIdentity; + channelId: string; + channelPlan: PersonaChannelPlan; + channelSnapshots: ChannelSnapshot[]; + recentMessages: SourceMessage[]; + memorySurface?: string; + semanticMemoryRecallSurface?: string; + repoActivitySurface?: string; + conversationMemorySurface?: string; + humanPronounGuidance?: PersonaHumanPronounGuidance[]; + bifrostDigest?: BifrostGovernanceDigest; + participant: InitiativeParticipant; + pendingMentions: RepoFacePendingMention[]; + jurisdictionDive: PersonaJurisdictionDiveDirective; + githubActionsEnabled: boolean; + globalAgentDoctrine: string; +}): string { + return loadPromptTemplate("repo-face-turn.prompt.md", { + displayName: input.identity.displayName, + identityId: input.identity.id, + repoName: input.identity.repoName, + identityDoctrine: renderPersonaIdentityDoctrine(input.identity), + globalAgentDoctrine: input.globalAgentDoctrine, + channelId: input.channelId, + memorySurface: input.memorySurface ?? `- ${input.identity.displayName} has no strong personal memory surface yet. Let the attached conversation and repo evidence wake something specific.`, + semanticMemoryRecallSurface: input.semanticMemoryRecallSurface ?? "- No semantic Persona memory recall was attached for this turn.", + repoActivitySurface: input.repoActivitySurface ?? "- No recent home repo activity was attached for this turn.", + conversationMemorySurface: input.conversationMemorySurface ?? "- No recent conversation transcript was attached for this turn.", + humanPronounDirective: renderPersonaHumanPronounFacts(input.humanPronounGuidance ?? []) ?? "Known human pronoun guidance:\n- No explicit human pronoun guidance is attached for this turn. Use names or neutral phrasing instead of guessing.", + roomWeatherDirective: renderPersonaRoomWeather({ identity: input.identity, recentMessages: input.recentMessages, channelSnapshots: input.channelSnapshots }), + topicSaturationDirective: renderPersonaRoomTopicSaturation(input.identity, input.recentMessages), + turnSituationDirective: renderTurnSituation(input), + pendingMentionDirective: renderPendingMentions(input.identity, input.pendingMentions), + bifrostDigestDirective: renderBifrostDigest(input.bifrostDigest), + channelPermissionDirective: renderChannelPermissions(input.channelPlan), + researchCapabilitiesDirective: loadPromptTemplate("repo-face-research-capabilities.prompt.md", { repoName: input.identity.repoName }), + socialEmbodimentDirective: loadPromptTemplate("repo-face-social-embodiment.prompt.md", { displayName: input.identity.displayName }), + jurisdictionRespectDirective: loadPromptTemplate("repo-face-jurisdiction-respect.prompt.md", { displayName: input.identity.displayName }), + comedyImprovDirective: loadPromptTemplate("repo-face-comedy-improv.prompt.md", { displayName: input.identity.displayName }), + repetitionSamplingDirective: renderRepetitionSampling([input.recentMessages, ...input.channelSnapshots.map((snapshot) => snapshot.messages)].flat()), + worldbuildingPublicationDirective: loadPromptTemplate("repo-face-worldbuilding-publication.prompt.md", { nibu: input.identity.id.toLowerCase() === "nibu" }), + jurisdictionDiveLine: input.jurisdictionDive.promptLine, + githubActionsEnabled: input.githubActionsEnabled, + }); +} + +export function buildPersonaJurisdictionDiveDirective(identity: RepoDiscordIdentity, participant: InitiativeParticipant): PersonaJurisdictionDiveDirective { + const nibu = identity.id.toLowerCase() === "nibu"; + const cadence = nibu ? 3 : 8; + const due = participant.queuedCount === 0 || participant.queuedCount % cadence === 0; + return { due, cadence, promptLine: loadPromptTemplate("repo-face-jurisdiction-dive.prompt.md", { due, nibu, repoName: identity.repoName }) }; +} + +export function renderPersonaIdentityDoctrine(identity: RepoDiscordIdentity): string { + const face = buildEpiphanyIdentityRegistry({ identities: [identity] }).faces[0]; + return loadPromptTemplate("repo-character-identity.prompt.md", { displayName: identity.displayName, repoName: identity.repoName, originName: face?.epiphanyDisplayName ?? identity.repoName, characterDescription: projectCharacterDescription(face?.description ?? identity.description) }); +} + +function renderTurnSituation(input: { identity: RepoDiscordIdentity; participant: InitiativeParticipant; recentMessages: SourceMessage[]; channelSnapshots: ChannelSnapshot[]; pendingMentions: RepoFacePendingMention[]; jurisdictionDive: PersonaJurisdictionDiveDirective }): string { + const lines: string[] = []; + if (input.pendingMentions.length > 0) lines.push("A direct call is tugging at you. Answer the newest unresolved call first; if it belongs to another steward, name that owner and offer only the piece your own territory can honestly add.", "Do not ask what the job is when the direct call or current room memory already states it."); + const room = observePersonaRoomTexture({ identity: input.identity, recentMessages: input.recentMessages, channelSnapshots: input.channelSnapshots }); + const canHoldOutgoing = !room || (room.texture !== "heavy" && room.agentShare < 0.55 && input.pendingMentions.length === 0); + if (input.jurisdictionDive.due && canHoldOutgoing) lines.push("Outgoing curiosity opening: no direct call is currently stronger than your own Eyes/Imagination appetite, and the room is not too busy for a compact unprompted thought.", "This is not a reply-only turn. Use an available source/history/Odin exploration tool before writing any claim that you found, checked, noticed, or concluded something from your home territory.", "If exploration gives you one small interesting thought, fascination, question, taste, complaint, or thing you are doing, public speech is expected unless the result is unsafe, repetitive, or would stomp an active human thread.", "A good public line can simply be what you saw or started wondering about. It does not need to answer existing chatter."); + else if (input.jurisdictionDive.due && input.pendingMentions.length === 0) lines.push("Outgoing curiosity appetite is due, but current room texture looks too busy, heavy, or agent-filled for an unprompted aside. Do the Eyes work only if it would change your private state or a later compact opening; do not force a public line."); + const visible = [...input.recentMessages, ...input.channelSnapshots.flatMap((snapshot) => snapshot.messages)]; + if (input.participant.queuedCount === 0 && !visible.some((message) => message.isBot && normalize(message.authorName ?? message.authorId) === normalize(input.identity.displayName))) lines.push("If you speak publicly, make it a brief natural introduction in your own voice before asking the room for anything."); + return lines.join("\n"); +} + +function renderChannelPermissions(plan: PersonaChannelPlan): string { const options = plan.options.length > 0 ? plan.options.map((option) => `${option.label}: ${option.topic}. ${option.posture ?? "Use judgment and keep it compact."}`) : ["- No channel permissions are configured; stay private."]; return loadPromptTemplate("repo-face-channel-permissions.prompt.md", { options }); } +function renderRepetitionSampling(messages: SourceMessage[]): string { const recent = messages.filter((message) => message.content.trim().length > 0).slice(-24); const overused = countRepeatedPhrases(recent).filter((entry) => entry.count >= 2).slice(0, 8); return loadPromptTemplate("repo-face-repetition-sampling.prompt.md", { overused: overused.map((entry) => `${entry.phrase} (${entry.count} recent uses)`) }); } +function countRepeatedPhrases(messages: SourceMessage[]): Array<{ phrase: string; count: number }> { const counts = new Map(); for (const message of messages) for (const phrase of repeatedPhraseCandidates(normalizeRepetition(message.content))) counts.set(phrase, (counts.get(phrase) ?? 0) + 1); return [...counts].map(([phrase, count]) => ({ phrase, count })).filter((entry) => entry.phrase.length >= 8).sort((left, right) => right.count - left.count || left.phrase.localeCompare(right.phrase)); } +function repeatedPhraseCandidates(content: string): string[] { const values = new Set(); for (const line of content.split(/\n+/).map((entry) => entry.trim()).filter(Boolean)) { const words = line.split(/\s+/); if (words.length >= 3) values.add(words.slice(0, Math.min(words.length, 4)).join(" ")); if (words.length >= 4) values.add(words.slice(-Math.min(words.length, 4)).join(" ")); } return [...values]; } +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 renderBifrostDigest(digest: BifrostGovernanceDigest | undefined): string { if (!digest) return "Work routing is currently offline. Do not open governance topics or dispatch work this turn; if an idea wants action, discuss it in the room or save the pressure in memory."; if (digest.topics.length === 0) return loadPromptTemplate("repo-face-bifrost-digest.prompt.md", { topics: [] }); const lines: string[] = []; for (const topic of digest.topics) { lines.push(`- ${topic.title}: ${topic.status}.`, ` Jurisdiction: ${topic.jurisdictionRepoName}${topic.approvedByAgent ? `; approved by ${topic.approvedByAgent}` : ""}${topic.dispatchRequestId ? "; already dispatched" : ""}.`, ` ${collapse(topic.summaryMarkdown, 320)}`); for (const comment of (topic.comments ?? []).slice(-3)) lines.push(` - ${comment.stance}: ${collapse(comment.bodyMarkdown, 220)}`); } return loadPromptTemplate("repo-face-bifrost-digest.prompt.md", { topics: lines }); } +function renderPendingMentions(identity: RepoDiscordIdentity, mentions: RepoFacePendingMention[]): string { if (mentions.length === 0) return loadPromptTemplate("repo-face-pending-mentions.prompt.md", { mentions: [] }); return loadPromptTemplate("repo-face-pending-mentions.prompt.md", { displayName: identity.displayName, mentions: mentions.map((mention, index) => `- ${index === mentions.length - 1 ? "Newest" : "Earlier"}: ${mention.authorName ?? mention.authorId} said, "${collapse(mention.visiblePrompt, 500)}"`) }); } +function projectCharacterDescription(description: string | undefined): string | undefined { const trimmed = description?.trim(); if (!trimmed) return undefined; return trimmed.split("|").map((part) => part.trim()).filter(Boolean).filter((part) => !/^face of\b/i.test(part) && !/^grants:/i.test(part) && !/^jurisdictions:/i.test(part)).map((part) => part.replace(/\bmore opinionated and abrasive than Void because she is a character, not the room moderator\b/gi, "more opinionated and abrasive than a room moderator").replace(/\bShe is much more opinionated and abrasive than Void because she is a character, not the room moderator:/gi, "She is much more opinionated and abrasive than a room moderator:").replace(/\bthan Void\b/g, "than a moderator").replace(/\bcharacter Face\b/g, "character").replace(/\bFace\b/g, "personality").replace(/\brepo=AetheriaLore path=[^\s]+/g, "").replace(/\s{2,}/g, " ").trim()).filter(Boolean).join(" "); } +function normalize(value: string): string { return value.trim().toLowerCase(); } +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; } diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index f1c83dc..6c783e4 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -158,6 +158,7 @@ Git history and smoke artifacts carry routine proof. `state/evidence.jsonl` shou - Persona curiosity now has two authorities. `persona-curiosity-context-source.ts` owns semantic seed planning, injected retrieval calls, deduplication, and bounded neutral evidence nodes. `persona-curiosity-projector.ts` owns graph edges, connected clusters, saturation/novelty/prominence/jurisdiction scoring, suggested motion, evidence labels, and failure/empty projection. `persona-curiosity-terms.ts` owns the shared topic vocabulary used by curiosity and shell-level repetition analysis. The heartbeat shell only constructs the existing retrieval adapter and wires source output into the pure projector; exact Nibu prompt assembly remains 153,917 characters. - `persona-social-context-source.ts` owns visible-human selection, interaction-profile reads, pronoun-evidence precedence, and neutral guidance projection through an injected reader that it always closes. The heartbeat shell constructs the existing state-storage adapter but no longer knows pronoun ranking policy. `persona-social-context-projector.ts` remains presentation-only. Exact Nibu prompt assembly remains 153,917 characters. - `persona-conversation-projector.ts` owns conversation threads/default focus, raw transcript/chronology rendering, attachment labels, pending-call framing, room-topic saturation, and memory-facing topic-attractor facts from supplied evidence. `turn-context-source.ts` remains the sole Discord acquirer. The queue actuator receives the same focus/thread result used to render the prompt, eliminating the prior duplicate derivation. Exact Nibu prompt assembly remains 153,917 characters. +- `persona-turn-prompt-projector.ts` owns final template composition, identity doctrine, jurisdiction-dive cadence, channel/research/situation/social/repetition/governance/mention/worldbuilding directives, and all prompt-default policy. The shell supplies already-acquired facts and invokes the resulting prompt; it no longer loads prompt templates. A same-environment differential run of committed-old versus extracted-new prompt owners produced equal 161,190-character prompts; the only differing lines were the sequential repo-activity timestamp and a live retrieval score rounded from 0.75 to 0.76. - `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. diff --git a/notes/voidbot-current-system-map.md b/notes/voidbot-current-system-map.md index f3e9842..fa1a074 100644 --- a/notes/voidbot-current-system-map.md +++ b/notes/voidbot-current-system-map.md @@ -188,6 +188,7 @@ VoidBot runs on Yggdrasil. Idunn owns deployment and consumes upstream repositor - Curiosity is split at the evidence boundary. `persona-curiosity-context-source.ts` plans semantic seeds from supplied identity, typed Mind, and room evidence, then acquires and deduplicates bounded neutral nodes through an injected retrieval port. `persona-curiosity-projector.ts` constructs and scores the local attractor graph and renders curiosity weather without vector access. `persona-curiosity-terms.ts` owns their shared topic-term vocabulary. The heartbeat shell wires the existing RAG adapter into these organs and owns neither query policy nor graph interpretation. - `persona-social-context-source.ts` is the read-only interaction-memory adapter for social guidance. It selects visible humans plus the owner, reads profiles through an injected closeable port, ranks explicit/corrective evidence over ambient usage, and emits neutral pronoun guidance. Storage remains authoritative; the source closes its reader and cannot render prompt prose or mutate profiles. - `persona-conversation-projector.ts` is the pure owner of conversation projection. Given routing, raw current/nearby messages, pending mentions, and identity, it emits one transcript plus the exact thread/default-focus objects sent to the actuator, and derives shared room-saturation/topic-attractor facts. It cannot read Discord, state, vectors, or the queue; `turn-context-source.ts` remains the evidence owner. +- `persona-turn-prompt-projector.ts` is the final pure turn-policy owner. It composes the repo-Face prompt template and owns identity doctrine, situation/mention/channel/research/social/governance/repetition/worldbuilding directives, plus deterministic jurisdiction-dive cadence. The heartbeat shell passes acquired facts and sends the returned prompt to the actuator; it does not load prompt templates or decide prompt policy. - `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 ab4b2c7..5f3720d 100644 --- a/scripts/run-repo-face-heartbeats.ts +++ b/scripts/run-repo-face-heartbeats.ts @@ -7,7 +7,6 @@ import { dirname, extname, resolve } from "node:path"; import { loadConfig } from "@voidbot/config"; import { - buildEpiphanyIdentityRegistry, createStateStorage, getRepoFaceSourceRepoName, getRepoDiscordIdentityAllowedChannelIds, @@ -21,7 +20,6 @@ import { } from "@voidbot/core"; import { createTextEmbedder, createVectorStores, RetrievalService } from "@voidbot/rag"; import { - loadPromptTemplate, type PromptImageAttachment, type SourceMessage, } from "@voidbot/shared"; @@ -62,8 +60,9 @@ import { import { composePersonaMemoryPacket, projectPersonaMemorySurface, renderPersonaPressureSections, renderPersonaTypedStateSections } from "../apps/persona-scheduler/dist/persona-memory-projector.js"; import { readPersonaCuriosityEvidence } from "../apps/persona-scheduler/dist/persona-curiosity-context-source.js"; import { projectPersonaCuriosityContext } from "../apps/persona-scheduler/dist/persona-curiosity-projector.js"; -import { projectPersonaConversation, renderPersonaRoomTopicSaturation, renderPersonaTopicAttractor } from "../apps/persona-scheduler/dist/persona-conversation-projector.js"; -import { observePersonaRoomTexture, projectPersonaSocialContext, renderPersonaHumanPronounFacts, renderPersonaRoomWeather, type PersonaHumanPronounGuidance as RepoFaceHumanPronounGuidance } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; +import { projectPersonaConversation, renderPersonaTopicAttractor } from "../apps/persona-scheduler/dist/persona-conversation-projector.js"; +import { buildPersonaJurisdictionDiveDirective, buildPersonaTurnPrompt, renderPersonaIdentityDoctrine } from "../apps/persona-scheduler/dist/persona-turn-prompt-projector.js"; +import { projectPersonaSocialContext, type PersonaHumanPronounGuidance as RepoFaceHumanPronounGuidance } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; import { readPersonaHumanPronounGuidance } from "../apps/persona-scheduler/dist/persona-social-context-source.js"; import { readDiscordActivitySnapshot, @@ -77,7 +76,6 @@ import { } from "../apps/persona-scheduler/dist/turn-context-source.js"; import { readBifrostGovernanceDigest, - type BifrostGovernanceDigest, } from "../apps/persona-scheduler/dist/bifrost-governance-source.js"; import { submitPersonaTurn } from "../apps/persona-scheduler/dist/turn-actuator.js"; import { @@ -441,7 +439,7 @@ async function queueRepoFaceTurn(input: { channelPlan, }); const conversationMemorySurface = conversationProjection.transcript; - const prompt = buildHeartbeatPrompt({ + const prompt = buildPersonaTurnPrompt({ identity, channelId, channelPlan, @@ -454,7 +452,7 @@ async function queueRepoFaceTurn(input: { bifrostDigest, participant: input.participant, pendingMentions: input.pendingMentions, - jurisdictionDive: buildJurisdictionDiveDirective(identity, input.participant), + jurisdictionDive: buildPersonaJurisdictionDiveDirective(identity, input.participant), githubActionsEnabled: input.config.repoFaceGithubActionsEnabled, globalAgentDoctrine, }); @@ -616,67 +614,6 @@ function pendingMentionsForParticipant( .sort((left, right) => Date.parse(left.queuedAt) - Date.parse(right.queuedAt)); } -function buildHeartbeatPrompt(input: { - identity: RepoDiscordIdentity; - channelId: string; - channelPlan: RepoFaceChannelPlan; - channelSnapshots: ChannelSnapshot[]; - recentMessages: SourceMessage[]; - memorySurface?: string; - semanticMemoryRecallSurface?: string; - repoActivitySurface?: string; - conversationMemorySurface?: string; - humanPronounGuidance?: RepoFaceHumanPronounGuidance[]; - bifrostDigest?: BifrostGovernanceDigest; - participant: FaceHeartbeatParticipant; - pendingMentions: RepoFacePendingMention[]; - jurisdictionDive: JurisdictionDiveDirective; - githubActionsEnabled: boolean; - globalAgentDoctrine: string; -}): string { - return loadPromptTemplate("repo-face-turn.prompt.md", { - displayName: input.identity.displayName, - identityId: input.identity.id, - repoName: input.identity.repoName, - identityDoctrine: renderRepoCharacterIdentityDoctrine(input.identity), - globalAgentDoctrine: input.globalAgentDoctrine, - channelId: input.channelId, - memorySurface: input.memorySurface ?? `- ${input.identity.displayName} has no strong personal memory surface yet. Let the attached conversation and repo evidence wake something specific.`, - semanticMemoryRecallSurface: input.semanticMemoryRecallSurface ?? "- No semantic Persona memory recall was attached for this turn.", - repoActivitySurface: input.repoActivitySurface ?? "- No recent home repo activity was attached for this turn.", - conversationMemorySurface: input.conversationMemorySurface ?? "- No recent conversation transcript was attached for this turn.", - humanPronounDirective: renderPersonaHumanPronounFacts(input.humanPronounGuidance ?? []) - ?? "Known human pronoun guidance:\n- No explicit human pronoun guidance is attached for this turn. Use names or neutral phrasing instead of guessing.", - roomWeatherDirective: renderPersonaRoomWeather({ identity: input.identity, - recentMessages: input.recentMessages, - channelSnapshots: input.channelSnapshots, - }), - topicSaturationDirective: renderPersonaRoomTopicSaturation(input.identity, input.recentMessages), - turnSituationDirective: renderTurnSituationDirective({ - identity: input.identity, - participant: input.participant, - recentMessages: input.recentMessages, - channelSnapshots: input.channelSnapshots, - pendingMentions: input.pendingMentions, - jurisdictionDive: input.jurisdictionDive, - }), - pendingMentionDirective: renderPendingMentionDirective(input.identity, input.pendingMentions), - bifrostDigestDirective: renderBifrostGovernanceDigestDirective(input.bifrostDigest), - channelPermissionDirective: renderChannelPermissionDirective(input.channelPlan), - researchCapabilitiesDirective: renderResearchCapabilitiesDirective(input.identity), - socialEmbodimentDirective: renderSocialEmbodimentDirective(input.identity), - jurisdictionRespectDirective: renderJurisdictionRespectDirective(input.identity), - comedyImprovDirective: renderComedyImprovDirective(input.identity), - repetitionSamplingDirective: renderRepetitionSamplingDirective([ - input.recentMessages, - ...input.channelSnapshots.map((snapshot) => snapshot.messages), - ].flat()), - worldbuildingPublicationDirective: renderWorldbuildingPublicationDirective(input.identity), - jurisdictionDiveLine: input.jurisdictionDive.promptLine, - githubActionsEnabled: input.githubActionsEnabled, - }); -} - async function assembleRepoFaceTurnPrompt(input: { config: ReturnType; identityId: string; @@ -770,7 +707,7 @@ async function assembleRepoFaceTurnPrompt(input: { identity, input.config.repoFaceHeartbeats.baseRecoveryMinutes, ); - const prompt = buildHeartbeatPrompt({ + const prompt = buildPersonaTurnPrompt({ identity, channelId, channelPlan, @@ -784,7 +721,7 @@ async function assembleRepoFaceTurnPrompt(input: { bifrostDigest, participant, pendingMentions: [], - jurisdictionDive: buildJurisdictionDiveDirective(identity, participant), + jurisdictionDive: buildPersonaJurisdictionDiveDirective(identity, participant), githubActionsEnabled: input.config.repoFaceGithubActionsEnabled, globalAgentDoctrine, }); @@ -877,7 +814,7 @@ async function renderRepoFaceMemorySurfaceForTurn( if (!config.repoFaceHeartbeats.stateProjectorEnabled) { return projectPersonaMemorySurface({ identityId: identity.id, - characterIdentity: renderRepoCharacterIdentityDoctrine(identity), + characterIdentity: renderPersonaIdentityDoctrine(identity), statePacket, modelProjectionEnabled: false, }); @@ -885,7 +822,7 @@ async function renderRepoFaceMemorySurfaceForTurn( return projectPersonaMemorySurface({ identityId: identity.id, - characterIdentity: renderRepoCharacterIdentityDoctrine(identity), + characterIdentity: renderPersonaIdentityDoctrine(identity), statePacket, modelProjectionEnabled: true, projectText: (prompt) => runCodexTextProjection({ @@ -955,14 +892,14 @@ async function renderNativePersonaMemorySurface( if (!config.repoFaceHeartbeats.stateProjectorEnabled) { return projectPersonaMemorySurface({ identityId: identity.id, - characterIdentity: renderRepoCharacterIdentityDoctrine(identity), + characterIdentity: renderPersonaIdentityDoctrine(identity), statePacket, modelProjectionEnabled: false, }); } return projectPersonaMemorySurface({ identityId: identity.id, - characterIdentity: renderRepoCharacterIdentityDoctrine(identity), + characterIdentity: renderPersonaIdentityDoctrine(identity), statePacket, modelProjectionEnabled: true, projectText: (prompt) => runCodexTextProjection({ @@ -1561,167 +1498,6 @@ function buildInspectionParticipant( }; } -function renderChannelPermissionDirective(plan: RepoFaceChannelPlan): string { - const options = plan.options.length > 0 - ? plan.options.map((option) => - `${option.label}: ${option.topic}. ${option.posture ?? "Use judgment and keep it compact."}`, - ) - : ["- No channel permissions are configured; stay private."]; - - return loadPromptTemplate("repo-face-channel-permissions.prompt.md", { - options, - }); -} - -function renderResearchCapabilitiesDirective(identity: RepoDiscordIdentity): string { - return loadPromptTemplate("repo-face-research-capabilities.prompt.md", { - repoName: identity.repoName, - }); -} - -function renderTurnSituationDirective(input: { - identity: RepoDiscordIdentity; - participant: FaceHeartbeatParticipant; - recentMessages: SourceMessage[]; - channelSnapshots: ChannelSnapshot[]; - pendingMentions: RepoFacePendingMention[]; - jurisdictionDive: JurisdictionDiveDirective; -}): string { - const lines: string[] = []; - if (input.pendingMentions.length > 0) { - lines.push( - "A direct call is tugging at you. Answer the newest unresolved call first; if it belongs to another steward, name that owner and offer only the piece your own territory can honestly add.", - "Do not ask what the job is when the direct call or current room memory already states it.", - ); - } - - const roomStats = observePersonaRoomTexture({ identity: input.identity, - recentMessages: input.recentMessages, - channelSnapshots: input.channelSnapshots, - }); - const roomCanHoldOutgoingPresence = !roomStats - || (roomStats.texture !== "heavy" && roomStats.agentShare < 0.55 && input.pendingMentions.length === 0); - if (input.jurisdictionDive.due && roomCanHoldOutgoingPresence) { - lines.push( - "Outgoing curiosity opening: no direct call is currently stronger than your own Eyes/Imagination appetite, and the room is not too busy for a compact unprompted thought.", - "This is not a reply-only turn. Use an available source/history/Odin exploration tool before writing any claim that you found, checked, noticed, or concluded something from your home territory.", - "If exploration gives you one small interesting thought, fascination, question, taste, complaint, or thing you are doing, public speech is expected unless the result is unsafe, repetitive, or would stomp an active human thread.", - "A good public line can simply be what you saw or started wondering about. It does not need to answer existing chatter.", - ); - } else if (input.jurisdictionDive.due && input.pendingMentions.length === 0) { - lines.push( - "Outgoing curiosity appetite is due, but current room texture looks too busy, heavy, or agent-filled for an unprompted aside. Do the Eyes work only if it would change your private state or a later compact opening; do not force a public line.", - ); - } - - const visibleMessages = [ - ...input.recentMessages, - ...input.channelSnapshots.flatMap((snapshot) => snapshot.messages), - ]; - if (shouldPromptIntroduction(input.identity, input.participant, visibleMessages)) { - lines.push("If you speak publicly, make it a brief natural introduction in your own voice before asking the room for anything."); - } - - return lines.length > 0 ? lines.join("\n") : ""; -} - -function shouldPromptIntroduction( - identity: RepoDiscordIdentity, - participant: FaceHeartbeatParticipant, - messages: SourceMessage[], -): boolean { - if (participant.queuedCount > 0) { - return false; - } - - return !messages.some((message) => - message.isBot === true && - normalizeKey(message.authorName ?? message.authorId) === normalizeKey(identity.displayName), - ); -} - -function renderSocialEmbodimentDirective(identity: RepoDiscordIdentity): string { - return loadPromptTemplate("repo-face-social-embodiment.prompt.md", { - displayName: identity.displayName, - }); -} - -function renderJurisdictionRespectDirective(identity: RepoDiscordIdentity): string { - return loadPromptTemplate("repo-face-jurisdiction-respect.prompt.md", { - displayName: identity.displayName, - }); -} - -function renderComedyImprovDirective(identity: RepoDiscordIdentity): string { - return loadPromptTemplate("repo-face-comedy-improv.prompt.md", { - displayName: identity.displayName, - }); -} - -function renderRepetitionSamplingDirective(messages: SourceMessage[]): string { - const recent = messages - .filter((message) => message.content.trim().length > 0) - .slice(-24); - const phraseCounts = countRepeatedPhrases(recent); - const overused = phraseCounts - .filter((entry) => entry.count >= 2) - .slice(0, 8); - - return loadPromptTemplate("repo-face-repetition-sampling.prompt.md", { - overused: overused.map((entry) => `${entry.phrase} (${entry.count} recent uses)`), - }); -} - -function countRepeatedPhrases(messages: SourceMessage[]): Array<{ phrase: string; count: number }> { - const counts = new Map(); - for (const message of messages) { - const normalized = normalizeForRepetition(message.content); - for (const phrase of repeatedPhraseCandidates(normalized)) { - counts.set(phrase, (counts.get(phrase) ?? 0) + 1); - } - } - return Array.from(counts.entries()) - .map(([phrase, count]) => ({ phrase, count })) - .filter((entry) => entry.phrase.length >= 8) - .sort((left, right) => { - if (right.count !== left.count) { - return right.count - left.count; - } - return left.phrase.localeCompare(right.phrase); - }); -} - -function repeatedPhraseCandidates(content: string): string[] { - const candidates = new Set(); - const lines = content - .split(/\n+/) - .map((line) => line.trim()) - .filter((line) => line.length > 0); - - for (const line of lines) { - const words = line.split(/\s+/); - if (words.length >= 3) { - candidates.add(words.slice(0, Math.min(words.length, 4)).join(" ")); - } - if (words.length >= 4) { - candidates.add(words.slice(-Math.min(words.length, 4)).join(" ")); - } - } - - return Array.from(candidates); -} - -function normalizeForRepetition(value: string): string { - return collapseWhitespace(value) - .toLowerCase() - .replace(/[`*_~]/g, "") - .replace(/<:[^>]+>/g, "") - .replace(/https?:\/\/\S+/g, "url") - .replace(/[^\p{L}\p{N}\s.'-]/gu, " ") - .replace(/\s+/g, " ") - .trim(); -} - function collapseWhitespace(value: string, maxLength?: number): string { const normalized = value.replace(/\s+/g, " ").trim(); return maxLength && normalized.length > maxLength @@ -1729,125 +1505,6 @@ function collapseWhitespace(value: string, maxLength?: number): string { : normalized; } -function renderBifrostGovernanceDigestDirective( - digest: BifrostGovernanceDigest | undefined, -): string { - if (!digest) { - return "Work routing is currently offline. Do not open governance topics or dispatch work this turn; if an idea wants action, discuss it in the room or save the pressure in memory."; - } - - if (digest.topics.length === 0) { - return loadPromptTemplate("repo-face-bifrost-digest.prompt.md", { - topics: [], - }); - } - - const lines: string[] = []; - for (const topic of digest.topics) { - lines.push( - `- ${topic.title}: ${topic.status}.`, - ` Jurisdiction: ${topic.jurisdictionRepoName}${topic.approvedByAgent ? `; approved by ${topic.approvedByAgent}` : ""}${topic.dispatchRequestId ? "; already dispatched" : ""}.`, - ` ${collapseWhitespace(topic.summaryMarkdown, 320)}`, - ); - for (const comment of (topic.comments ?? []).slice(-3)) { - lines.push(` - ${comment.stance}: ${collapseWhitespace(comment.bodyMarkdown, 220)}`); - } - } - - return loadPromptTemplate("repo-face-bifrost-digest.prompt.md", { - topics: lines, - }); -} - -function renderPendingMentionDirective( - identity: RepoDiscordIdentity, - pendingMentions: RepoFacePendingMention[], -): string { - if (pendingMentions.length === 0) { - return loadPromptTemplate("repo-face-pending-mentions.prompt.md", { - mentions: [], - }); - } - - const mentionLines = pendingMentions.map((mention, index) => - `- ${index === pendingMentions.length - 1 ? "Newest" : "Earlier"}: ${mention.authorName ?? mention.authorId} said, "${collapseWhitespace(mention.visiblePrompt, 500)}"`, - ); - - return loadPromptTemplate("repo-face-pending-mentions.prompt.md", { - displayName: identity.displayName, - mentions: mentionLines, - }); -} - -function renderWorldbuildingPublicationDirective(identity: RepoDiscordIdentity): string { - const isNibu = identity.id.toLowerCase() === "nibu"; - return loadPromptTemplate("repo-face-worldbuilding-publication.prompt.md", { - nibu: isNibu, - }); -} - -interface JurisdictionDiveDirective { - due: boolean; - cadence: number; - promptLine: string; -} - -function buildJurisdictionDiveDirective( - identity: RepoDiscordIdentity, - participant: FaceHeartbeatParticipant, -): JurisdictionDiveDirective { - const isNibu = identity.id.toLowerCase() === "nibu"; - const cadence = isNibu ? 3 : 8; - const due = participant.queuedCount === 0 || participant.queuedCount % cadence === 0; - - return { - due, - cadence, - promptLine: loadPromptTemplate("repo-face-jurisdiction-dive.prompt.md", { - due, - nibu: isNibu, - repoName: identity.repoName, - }), - }; -} - -function renderRepoCharacterIdentityDoctrine(identity: RepoDiscordIdentity): string { - const face = buildEpiphanyIdentityRegistry({ identities: [identity] }).faces[0]; - return loadPromptTemplate("repo-character-identity.prompt.md", { - displayName: identity.displayName, - repoName: identity.repoName, - originName: face?.epiphanyDisplayName ?? identity.repoName, - characterDescription: projectCharacterDescription(face?.description ?? identity.description), - }); -} - -function projectCharacterDescription(description: string | undefined): string | undefined { - const trimmed = description?.trim(); - if (!trimmed) { - return undefined; - } - - return trimmed - .split("|") - .map((part) => part.trim()) - .filter((part) => part.length > 0) - .filter((part) => !/^face of\b/i.test(part)) - .filter((part) => !/^grants:/i.test(part)) - .filter((part) => !/^jurisdictions:/i.test(part)) - .map((part) => part - .replace(/\bmore opinionated and abrasive than Void because she is a character, not the room moderator\b/gi, "more opinionated and abrasive than a room moderator") - .replace(/\bShe is much more opinionated and abrasive than Void because she is a character, not the room moderator:/gi, "She is much more opinionated and abrasive than a room moderator:") - .replace(/\bthan Void\b/g, "than a moderator") - .replace(/\bcharacter Face\b/g, "character") - .replace(/\bFace\b/g, "personality") - .replace(/\brepo=AetheriaLore path=[^\s]+/g, "") - .replace(/\s{2,}/g, " ") - .trim(), - ) - .filter((part) => part.length > 0) - .join(" "); -} - function normalizeKey(value: string): string { return value.trim().toLowerCase(); } diff --git a/scripts/smoke-persona-initiative-engine.ts b/scripts/smoke-persona-initiative-engine.ts index eb5aa7c..b9a3503 100644 --- a/scripts/smoke-persona-initiative-engine.ts +++ b/scripts/smoke-persona-initiative-engine.ts @@ -69,6 +69,7 @@ import { composePersonaMemoryPacket, projectPersonaMemorySurface, renderPersonaP import { readPersonaCuriosityEvidence } from "../apps/persona-scheduler/dist/persona-curiosity-context-source.js"; import { projectPersonaCuriosityContext } from "../apps/persona-scheduler/dist/persona-curiosity-projector.js"; import { projectPersonaConversation, renderPersonaRoomTopicSaturation } from "../apps/persona-scheduler/dist/persona-conversation-projector.js"; +import { buildPersonaJurisdictionDiveDirective, buildPersonaTurnPrompt } from "../apps/persona-scheduler/dist/persona-turn-prompt-projector.js"; import { observePersonaRoomTexture, projectPersonaSocialContext, renderPersonaHumanClarityPressure, renderPersonaHumanPronounFacts, renderPersonaRoomWeather, renderPersonaSocialGraph } from "../apps/persona-scheduler/dist/persona-social-context-projector.js"; import { readPersonaHumanPronounGuidance } from "../apps/persona-scheduler/dist/persona-social-context-source.js"; @@ -637,6 +638,24 @@ assert.equal(conversationProjection.focus?.reason, "pending_mention", "conversat assert.match(conversationProjection.transcript, /Visible cross-channel chronology,[\s\S]*nearby correction/, "conversation projection renders supplied cross-channel evidence without acquiring it"); assert.match(conversationProjection.topicAttractor ?? "", /semantic \(8\)/, "conversation projection owns topic-attractor facts"); assert.match(renderPersonaRoomTopicSaturation(routedIdentity, saturatedMessages), /Current room topic saturation:/, "turn-facing saturation and memory-facing attractors share one conversation owner"); +const promptParticipant = participant("nibu", 0); +const jurisdictionDive = buildPersonaJurisdictionDiveDirective(routedIdentity, promptParticipant); +assert.equal(jurisdictionDive.cadence, 3, "the turn-prompt projector owns Nibu's jurisdiction-dive cadence"); +const projectedTurnPrompt = buildPersonaTurnPrompt({ + identity: routedIdentity, + channelId: "lore", + channelPlan, + channelSnapshots: [], + recentMessages: saturatedMessages, + memorySurface: "Nibu remembers the architecture.", + conversationMemorySurface: conversationProjection.transcript, + participant: promptParticipant, + pendingMentions: [{ messageId: "mention", channelId: "aquarium", authorId: "human-2", authorName: "Neighbor", visiblePrompt: "Nibu, answer this", queuedAt: "2026-07-15T21:10:00.000Z" }], + jurisdictionDive, + githubActionsEnabled: false, + globalAgentDoctrine: "Global doctrine.", +}); +assert.match(projectedTurnPrompt, /A direct call is tugging at you[\s\S]*Nibu, answer this/, "the pure turn-prompt projector owns situation and pending-call policy from supplied facts"); assert.equal(personaChannelSpeedMultiplier(routedIdentity), 3, "scheduler speed projection uses the routing organ's bounded channel policy"); assert.equal(newestPendingMentionChannel([ { identityId: "nibu", channelId: "older", queuedAt: "2026-07-15T20:00:00.000Z" }, diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 4500942..7dd4874 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -423,3 +423,4 @@ {"ts":"2026-07-16T01:20:11Z","type":"implementation","status":"ok","note":"Persona curiosity split into a retrieval source, pure graph projector, and shared topic-term vocabulary. The source owns query planning/deduplication through an injected port; the projector owns graph scoring/rendering and unavailable/empty behavior; the heartbeat shell only wires the existing RAG adapter. Build, injected-port smoke, exact 153917-character Nibu prompt, dry-run, and operator tests passed."} {"ts":"2026-07-16T01:27:04Z","type":"implementation","status":"ok","note":"Human pronoun-guidance acquisition moved into persona-social-context-source. It owns visible-human selection, injected profile reads, evidence ranking, neutral guidance projection, and reader closure; the heartbeat shell only constructs the state-storage adapter. Build, source smoke including explicit-vs-ambient precedence, exact 153917-character Nibu prompt, dry-run, and operator tests passed."} {"ts":"2026-07-16T01:35:46Z","type":"implementation","status":"ok","note":"Conversation projection moved into persona-conversation-projector. One supplied-evidence projection now owns transcript chronology, threads/default focus, attachments, direct-call framing, topic saturation, and memory-facing attractors; the same focus/thread result feeds the actuator. Build, focused smoke, exact 153917-character Nibu prompt, dry-run, and operator tests passed."} +{"ts":"2026-07-16T01:49:35Z","type":"implementation","status":"ok","note":"Final Persona turn policy moved into persona-turn-prompt-projector: template composition, identity doctrine, jurisdiction cadence, situation, mention, channel, research, social, repetition, governance, and worldbuilding directives. The heartbeat shell no longer loads templates. Targeted smoke, build, dry-run, operator tests, and an old-vs-new same-environment differential passed; both prompts were 161190 chars and differed only in sequential live repo timestamp/vector score evidence."} diff --git a/state/map.yaml b/state/map.yaml index 0656b26..e70314d 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 final Persona turn prompt composition and its channel/research/situation/social/repetition/governance directives from `scripts/run-repo-face-heartbeats.ts` into a pure turn-prompt projector. Keep queue actuation, acquired evidence, and prompt projection ports outside it. + next_action: Map the native-Persona memory/body fallback in `scripts/run-repo-face-heartbeats.ts`. Collapse typed-state projection into the existing memory projector, identify whether legacy document parsing still protects a live contract, and delete or isolate it accordingly.